How do I loop through dynamic test cases in Jest?
I have test cases like the following how do I dynamically create jest test case using it/test
methods.
Here is what I have tried , However it just passes without excuting the test cases in the loop.
const mymodule = require('mymodule'); const testCases = [ {q: [2, 3],r: 5}, {q: [1, 2],r: 3}, {q: [7, 0],r: 7}, {q: [4, 4],r: 8} ]; describe("Test my Math module", () => { test("test add method", () => { for (let i = 0; i < testCases.length; i++) { const { q,r } = testCases[i]; it(`should add ${q[0]},${q[1]} to ${expected}`, () => { const actual = mymodule.add(q[0] + q[1]); expect(actual).toBe(expected); }); } }); });
3 4 Unfortunately the same is not possible when looping through dynamic test cases generated from an async operation. :( github.com/facebook/jest/issues/1619#issuecomment-358576732 – Kevin Farrugia Aug 22 '18 at 7:21
Jest is a Javascript Testing Framework by Facebook. It is used most commonly for unit testing. Unit testing is when you provide input to a unit of code (usually, a function) and match the output with the expected output.
If you use for each, then your entire test will fail on the first case failure, and you will not know which one failed quickly. That's not completely true. You can put an it inside a forEach loop and get the same behavior. Really nice solution. Thanks. Thanks.
Ideally, you want 1 positive where the 2 numbers equal the sum, and a failure where you pass a string or something and throw an error. TL/DR; You don't need 4 tests that all do the same thing. Also, you need to pull the looped test cases out of the parent test for the loop to work. This will work just fine:
There's an in-built way to do this: test.each(table)(name, fn, timeout)
e.g.
test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( '.add(%i, %i)', (a, b, expected) => { expect(a + b).toBe(expected); }, );
where each inner array in the 2D array is passed as args to the test function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With