Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Jest tests sequentially?

Tags:

jestjs

People also ask

Does Jest run tests sequentially?

Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.

How do you run Jest tests in sequence?

If you want to run files in sequence as well, run Jest with the --runInBand command line flag. ( -i does the same thing.) Doing this, the scheduler might still run them in a different order from run to run.

Does Jest run concurrently?

To speed-up your tests, Jest can run them in parallel. By default, Jest will parallelise tests that are in different files. IMPORTANT: Paralellising tests mean using different threads to run test-cases simultaneously.

How do I run a Jest test for a specific file?

In order to run a specific test, you'll need to use the jest command. npm test will not work. To access jest directly on the command line, install it via npm i -g jest-cli or yarn global add jest-cli . Then simply run your specific test with jest bar.


CLI options are documented and also accessible by running the command jest --help.

You'll see the option you are looking for : --runInBand.


I'm still getting familiar with Jest, but it appears that describe blocks run synchronously whereas test blocks run asynchronously. I'm running multiple describe blocks within an outer describe that looks something like this:

describe
    describe
        test1
        test2

    describe
        test3

In this case, test3 does not run until test2 is complete because test3 is in a describe block that follows the describe block that contains test2.


It worked for me ensuring sequential running of nicely separated to modules tests:

1) Keep tests in separated files, but without spec/test in naming.

|__testsToRunSequentially.test.js
|__tests
   |__testSuite1.js
   |__testSuite2.js
   |__index.js

2) File with test suite also should look like this (testSuite1.js):

export const testSuite1 = () => describe(/*your suite inside*/)

3) Import them to testToRunSequentially.test.js and run with --runInBand:

import { testSuite1, testSuite2 } from './tests'

describe('sequentially run tests', () => {
   testSuite1()
   testSuite2()
})

Use the serial test runner:

npm install jest-serial-runner --save-dev

Set up jest to use it, e.g. in jest.config.js:

module.exports = {
   ...,
   runner: 'jest-serial-runner'
};

You could use the project feature to apply it only to a subset of tests. See https://jestjs.io/docs/en/configuration#projects-arraystring--projectconfig