Easily run the same unit test with different test data.
Not tied to a specific library, it can be used with
// sum.js
export const sum = (a, b) => a + b;
// sum.test.js
import scenarios from "test-scenarios";
describe("sum", () => {
scenarios([
{ a: 1, b: 2, result: 3 },
{ a: -1, b: 1, result: 0 }
], ({ a, b, result }, scenarioIndex) => {
describe(`Case ${scenarioIndex}: when ${a} and ${b} are passed`, () => {
it(`should return ${result}`, () => {
expect(sum(a, b)).toEqual(result);
});
});
});
});
Example output
PASS ./sum.test.js
sum
Case 0: when 1 and 2 are passed
✓ should return 3 (4ms)
Case 1: when -1 and 1 are passed
✓ should return 0
scenarios(testScenarios, testsFn)
testScenarios
:any
contains the test data for every scenario.testsFn
:Function
the test function to run each time with different data, it can be a wholedescribe
block or multipleit
/test
wrapped into a function. It will be invoked with:parameters
:any
the data for the scenarioindex
:number
the scenario index
You can achieve the same result as the above by using the following syntax:
describe.each([
{ a: 1, b: 2, result: 3 },
{ a: -1, b: 1, result: 0 }
])('sum', ({ a, b, result }) => {
describe(`When ${a} and ${b} are passed`, () => {
it(`should return ${result}`, () => {
expect(sum(a, b)).toEqual(result);
});
});
});
More info on describe.each and test.each.