Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest looping through dynamic test cases

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);                 });             }         });          }); 
like image 353
Mehari Mamo Avatar asked Aug 16 '17 12:08

Mehari Mamo


People also ask

Is it possible to loop through dynamic test cases generated from async?

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

What is the use of a jest framework?

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.

Should I use foreach or foreach loop in tests?

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.

How many tests do I need for a loop to work?

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:


1 Answers

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.

like image 110
justin Avatar answered Oct 11 '22 13:10

justin