How to Run a Single Test Using Jest

How do I run a single test using Jest? - Stack OverflowI have a test named works with nested children within the file fix-order-test.js.

When I run the following command, it executes all the tests in the file:

jest fix-order-test How can I run only a single test using Jest? The following command does not work as it searches for a file that matches the regex specified:

jest ‘works with nested children’

I need to know how to use jest run single test.

To run a single test from the command line, you can use the --testNamePattern or -t flag with Jest:


jest -t 'works with nested children'

This will run only the tests that match the name pattern you provide, as documented in Jest. This is the simplest way to make Jest run a single test.

Alternatively, you can use Jest’s watch mode by running:


jest --watch

In watch mode, you can press p to filter tests by file name or t to run a single test by its name. If your test is within a describe block, specify both the describe and it strings like so:


jest -t '<describeString> <itString>'

This way, you can be more specific with Jest to run a single test within a particular block.

Adding to what Jacqueline mentioned, if Jest is running as a script command, such as npm test, you need to use the following command to run a specific test:


npm test -- -t "works with nested children"

This will ensure Jest runs a single test by using the -t flag within an npm script. It’s a handy approach when working with predefined npm scripts.

Great points, Jacqueline and Ambika! Another way to make Jest run a single test is by using the .only method within your test file. You can modify your test like this:


it.only('works with nested children', () => {

// your test code here

});

This tells Jest to run only this specific test. Then, you can simply run your npm script:


npm run test

Using it.only is particularly useful when you want to focus on a single test during development and debugging sessions.