QUnit.test.each()

version added: 2.16.0

Description

QUnit.test.each( name, dataset, callback )
QUnit.test.only.each( name, dataset, callback )
QUnit.test.skip.each( name, dataset, callback )
QUnit.test.todo.each( name, dataset, callback )

Add tests using a data provider.

parameter description
name (string) Title of unit being tested
dataset (array) Array or object of data values passed to each test case
callback (function) Function to close over assertions

Callback parameters

parameter description
assert (object) A new instance object with the assertion methods
data (any) Data value

Use this method to add multiple tests that are similar, but with different data passed in.

QUnit.test.each() generates multiple calls to QUnit.test() internally, and has all the same capabilities such support for async functions, returning a Promise, and the assert argument.

Each test case is passed one value of your dataset.

The only, skip, and todo variants are also available, as QUnit.test.only.each, QUnit.test.skip.each, and QUnit.test.todo.each respectively.

Examples

Basic data provider

function isEven( x ) {
  return x % 2 === 0;
}

QUnit.test.each( "isEven()", [ 2, 4, 6 ], ( assert, data ) => {
  assert.true( isEven( data ), `${data} is even` );
});

Array data provider

The original array is passed to your callback. Array destructuring can be used to unpack the data array, directly from the callback signature.

function square( x ) {
  return x * x;
}

QUnit.test.each( "square()", [
  [ 2, 4 ],
  [ 3, 9 ]
], ( assert, [ value, expected ] ) => {
  assert.equal( square( value ), expected, `${value} squared` );
});

Object data provider

QUnit.test.each( "isEven()", {
  caseEven: [ 2, true ],
  caseNotEven: [ 3, false ]
}, ( assert, [ value, expected ] ) => {
  assert.strictEqual( isEven( value ), expected );
});

Async functions with each()

function isEven( x ) {
  return x % 2 === 0;
}

async function isAsyncEven( x ) {
  return new Promise( resolve => {
    resolve( isEven( x ) );
  } );
}

QUnit.test.each( "isAsyncEven()", [ 2, 4 ], async ( assert, data ) => {
  assert.true( await isAsyncEven( data ), `${data} is even` );
});

Return a Promise from each callback, using classic ES5 syntax:

function isEven( x ) {
  return x % 2 === 0;
}

function isAsyncEven( x ) {
  return new Promise( function ( resolve ) {
    resolve( isEven( x ) );
  } );
}

QUnit.test.each( "isAsyncEven()", [ 2, 4 ], ( assert, value ) => {
  return isAsyncEven( value ).then( ( result ) => {
    assert.true( result, `${value} is even` );
  } );
});