Search⌘ K

Data-driven Tests

Explore how to write data-driven tests in TypeScript using Jest by running the same test logic with different data sets. Understand using forEach and custom utility functions to automate repetitive tests, ensuring validation functions behave as expected for various inputs.

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:

C++
[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 ...