I have a very large array of JSON objects. I need to run Jest tests on each individual element. I tried iterating through the array first and then write the tests in the loop as such:
JavaScript
x
11
11
1
describe("Tests", (f) => {
2
it("has all fields and they are valid", () => {
3
expect(f.portions! >= 0).toBeTruthy();
4
expect(f.name.length > 0 && typeof f.name === "string").toBeTruthy();
5
});
6
7
it("has an image", () => {
8
expect(f.image).toBeTruthy();
9
});
10
});
11
However with this code Jest complains that ” Your test suite must contain at least one test.”
Do I have to loop over this array for every single test I have?
Advertisement
Answer
Jest does have describe.each
, test.each
and it.each
methods for your needs. It allows you to make same tests with different input/output.
https://jestjs.io/docs/api#describeeachtablename-fn-timeout
Examples :
With global describe.each :
JavaScript
1
13
13
1
const params = [
2
[true, false, false],
3
[true, true, true],
4
[false, true, false],
5
[false, false, true],
6
];
7
8
describe.each(params)('With params %s, %s, %s', (a, b, c) => {
9
it(`${a} === ${b} should be ${c}`, () => {
10
expect(a === b).toBe(c);
11
});
12
});
13
Output :
JavaScript
1
10
10
1
PASS test/integration-tests/test.spec.ts (5.938s)
2
With params true, false, false
3
√ true === false should be false (2ms)
4
With params true, true, true
5
√ true === true should be true
6
With params false, true, false
7
√ false === true should be false (1ms)
8
With params false, false, true
9
√ false === false should be true
10
Or with simple it.each :
JavaScript
1
13
13
1
const params = [
2
[true, false, false],
3
[true, true, true],
4
[false, true, false],
5
[false, false, true],
6
];
7
8
describe('Dumb test', () => {
9
it.each(params)('%s === %s should be %s', (a, b, c) => {
10
expect(a === b).toBe(c);
11
});
12
});
13
Output :
JavaScript
1
7
1
PASS test/integration-tests/test.spec.ts
2
Dumb test
3
√ true === false should be false (2ms)
4
√ true === true should be true
5
√ false === true should be false
6
√ false === false should be true
7