QUnit.test.each()
version added: 2.16.0.
Description
QUnit.test.each( name, dataset, callback )
QUnit.test.only.each( name, dataset, callback )
QUnit.test.todo.each( name, dataset, callback )
QUnit.test.skip.each( name, dataset, callback )
QUnit.test.if.each( name, condition, dataset, callback )
Add tests using a data provider.
parameter | description |
---|---|
name (string) |
Title of unit being tested |
dataset (array or object) |
Array or object of data values passed to each test case |
callback (function) |
Function that performs the test |
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
, todo
, skip
, and if
variants are also available, as QUnit.test.only.each
, QUnit.test.todo.each
, QUnit.test.skip.each
, and QUnit.test.if.each
respectively.
Changelog
UNRELEASED | Add automatic labels for primitive values in arrays. |
QUnit 2.16.0 | Introduce QUnit.test.each() . |
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`);
});
QUnit.test.each('truthy', ['a', 42, true, Infinity], (assert, data) => {
assert.true(!!data);
});
QUnit.test.each('falsy', [false, null], (assert, data) => {
assert.false(!!data);
});
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 isEven(x);
}
QUnit.test.each('isAsyncEven()', [2, 4], async (assert, data) => {
assert.true(await isAsyncEven(data), `${data} is even`);
});
Or in classic ES5 syntax, by returning a Promise from each callback:
function isEven (x) {
return x % 2 === 0;
}
function isAsyncEven (x) {
return Promise.resolve(isEven(x));
}
QUnit.test.each('isAsyncEven()', [2, 4], function (assert, data) {
return isAsyncEven(data).then(function (result) {
assert.true(result, data + ' is even');
});
});