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:
describe("Tests", (f) => { it("has all fields and they are valid", () => { expect(f.portions! >= 0).toBeTruthy(); expect(f.name.length > 0 && typeof f.name === "string").toBeTruthy(); }); it("has an image", () => { expect(f.image).toBeTruthy(); }); });
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 :
const params = [ [true, false, false], [true, true, true], [false, true, false], [false, false, true], ]; describe.each(params)('With params %s, %s, %s', (a, b, c) => { it(`${a} === ${b} should be ${c}`, () => { expect(a === b).toBe(c); }); });
Output :
PASS test/integration-tests/test.spec.ts (5.938s) With params true, false, false √ true === false should be false (2ms) With params true, true, true √ true === true should be true With params false, true, false √ false === true should be false (1ms) With params false, false, true √ false === false should be true
Or with simple it.each :
const params = [ [true, false, false], [true, true, true], [false, true, false], [false, false, true], ]; describe('Dumb test', () => { it.each(params)('%s === %s should be %s', (a, b, c) => { expect(a === b).toBe(c); }); });
Output :
PASS test/integration-tests/test.spec.ts Dumb test √ true === false should be false (2ms) √ true === true should be true √ false === true should be false √ false === false should be true