Arghajeet Bhattacharya
Arghajeet Bhattacharya

Reputation: 241

How to run same test multiple times using jest

I am using jest to run my test suite (with back-end as Node.js & express). Below is my code:

const puppeteer = require ('puppeteer');

test('testing login function', async () => {
    const browser = await puppeteer.launch ({  
        headless: true,
        args: ['--no-sandbox']
  });

    const page = await browser.newPage();

    await page.type('#username', 'admin');
    await page.type('#password', 'password');

    await page.click('login-button');

    await page.waitFor('.card');

    expect(texthead).toEqual('Welcome to webpage');

    await browser.close();
});

I am trying to run this same test multiple times at once, is there a way using it by jest, or maybe using other tools.

Upvotes: 24

Views: 31009

Answers (4)

Ohhh
Ohhh

Reputation: 668

Jest has a built in method for this using .each(). https://jestjs.io/docs/api#testeachtablename-fn-timeout

If you want to change the parameters of each test, you can pass an array of test parameters to .each([1,2,3]). If this is un-necessary, just fill the array with null.

test.each(Array(100).fill(null))('may be flaky test', async () => {})

This can optionally be run in parallel using .concurrent test.concurrent.each(Array(100).fill(null))('may be flaky test', async () => {})

Upvotes: 20

Brady Dowling
Brady Dowling

Reputation: 5532

If you're looking for something that will essentially stress test a single test (looking for test flakiness like I was) then you could use the following one-liner in your terminal, which of course uses bash and Jest together.

for i in {1..100}; do npx jest <test_file> --silent || (echo "Failed after $i attempts" && break); done

This specific command requires you to have npx installed and it uses the --silent option but you can change it as you please.

Upvotes: 36

gqstav
gqstav

Reputation: 2072

npx installed packages over and over and I wanted to time if my change improved the test speed. It's not great, but what I did was putting a command in the package.json

"jest": "jest <file_path> --silent"

and then borrowed the script from Brady as

for i in {1..100}; do yarn jest || (echo 'Failed after $i attempts' && break); done

I wrapped it in a timer, but that's not necessary really.

Upvotes: 3

Herman Starikov
Herman Starikov

Reputation: 2756

If you don't want tests run sequentially, you can use Promise.all. Here is a quick example of how you could refactor your code.

const runTheTest = async () => { 
  const browser = await puppeteer.launch ({
    headless: true, args: ['--no-sandbox'] 
  });
  .......
  return browser.close();
}

test('testing login function', async () => { 
  const testRuns = []
  for (let index = 0; index < NUMBER_OF_RUNS; index++) {
    testRuns.push(runTheTest())
  }
  return Promise.all(testRuns);
})

Upvotes: 6

Related Questions