Performing tests for similar scenarios can often lead to a tiring repetition of code. Here, table-driven tests offer an efficient solution. This testing method is designed to minimise repeated code by building a series of tests on a data basis.
The describe.each
method by Jest is a useful tool that allows for the creation of test suites that use different data but verify the same functionality.
There are two main approaches to the syntax that can be used here:
On the one hand, it is possible to construct a data table as an array in which string interpolation is worked. The Jest documentation provides an illustrative example for this.
An alternative and often considered more elegant method is the use of an array of objects as a test table. Each object represents input values and the expected result.
An example would look like this:
1describe.each([
2 {a: 1, b: 1, expected: 2},
3 {a: 1, b: 2, expected: 3},
4 {a: 2, b: 1, expected: 3},
5])('.add($a, $b)', ({a, b, expected}) => {
6 test(`returns ${expected}`, () => {
7 expect(a + b).toBe(expected);
8 });
9
10 test(`does not return more than ${expected}`, () => {
11 expect(a + b).not.toBeGreaterThan(expected);
12 });
13
14 test(`does not return less than ${expected}`, () => {
15 expect(a + b).not.toBeLessThan(expected);
16 });
17});
Furthermore, tagged template literals can be used to make test specifications clearer.
An example would be:
1describe.each`
2 a | b | expected
3 ${1} | ${1} | ${2}
4 ${1} | ${2} | ${3}
5 ${2} | ${1} | ${3}
6`('$a + $b', ({a, b, expected}) => {
7 test(`returns ${expected}`, () => {
8 expect(a + b).toBe(expected);
9 });
10
11 test(`does not return more than ${expected}`, () => {
12 expect(a + b).not.toBeGreaterThan(expected);
13 });
14
15 test(`does not return less than ${expected}`, () => {
16 expect(a + b).not.toBeLessThan(expected);
17 });
18});
These examples demonstrate how Jest enables table-driven tests to simplify the creation of compact and dynamic test suites.