...

/

Data-driven Tests

Data-driven Tests

Learn how to use data-driven tests in TypeScript to run the same test multiple times with different input values.

Using forEach for repetitive tests

Quite often, we need the same test to be run multiple times, just with different input values.

As an example of this, consider the following test:

Press + to interact
hello_jest.spec.ts
tsconfig.json
[1, 2, 3, 4, 5].forEach((value: number) => {
it(`${value} should be less than 5`, () => {
expect(value).toBeLessThan(5);
});
});
  • We define an array with the numbers one through five on line 1. We are then calling the forEach function, which takes a function as an argument and will execute that function once for each value in the array.

  • Note how we have then defined a test within this forEach function on lines 2–4, and the test is expecting that the value passed in should be less than 5.

  • Note, too, how we have used a template string in the actual name of the test on line 2 so that we can distinguish these tests ...