827

I have a test 'works with nested children' within the file fix-order-test.js.

Running the below runs all the tests in the file.

jest fix-order-test

How do I run only a single test? The below does not work as it searches for a file of the regex specified.

jest 'works with nested children'
vijayst
  • 20,359
  • 18
  • 69
  • 113

26 Answers26

955

From the command line, use the --testNamePattern or -t flag:

jest -t 'fix-order-test'

This will only run tests that match the test name pattern you provide. It's in the Jest documentation.

Another way is to run tests in watch mode, jest --watch, and then press P to filter the tests by typing the test file name or T to run a single test name.


If you have an it inside of a describe block, you have to run

jest -t '<describeString> <itString>'
Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • I am getting unrecognized options for -t. Yes, the documentation does mention it. The flag has been added in 16.0. I am on the latest version. jest -help does not seem to mention the flag. Thanks. – vijayst Apr 01 '17 at 14:42
  • 34
    Just a note that this is the test pattern for the specific test name inside `it()` function and not the file name. Which is what I thought. – HussienK Jan 26 '18 at 20:16
  • 179
    If using npm test, you need to do `npm test -- -t "fix order test"` – Sarsaparilla Jun 21 '18 at 01:39
  • 14
    This works for me but it also skips every single other test in the project which is slow for large projects. Specifying a specific test file that the test is in really helps: `./node_modules/.bin/jest --config=./.jest.config.json ./src/x/y/sites.js/sitesWorker.test.js -t 'given only incorrect sites'` – fIwJlxSzApHEZIl May 08 '19 at 20:36
  • Works for me with w/o specifying , i have noticed it is magnitudes slower than mocha's grep (-g 'searchString') - but i'll take it :-) – schmoopy Mar 26 '20 at 17:42
  • 4
    Not sure if this was the case back then but, now, if you drop the `-t` it'll run only the tests you care about without skipping all the rest. – Carter Aug 01 '20 at 15:04
  • For a full npm run-scripts based command, use `npm run test -- --debug --coverage=false -i src/test_file.test.js` – Jianyu Sep 20 '20 at 09:01
  • `jest -t testName` did not work for me but running `jest --watch` and `P` for the file name worked great. – Ian Jun 22 '21 at 23:16
  • that works for me -> `npm test file_test.js` – Ezequiel De Simone Jan 21 '22 at 16:21
  • agree you need to drop the -t, otherwise it just runs every single test – stackers Jun 22 '22 at 17:58
  • So... i add `.only` to my describe block.. `describe('.only ....`. Then add `-t=\.only` – nawlbergs Dec 23 '22 at 17:06
319

Jest documentation recommends the following:

If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. In Jest it's simple to run only one test - just temporarily change that test command to a test.only

test.only('this will be the only test that runs', () => {
   expect(true).toBe(false);
});

or

it.only('this will be the only test that runs', () => {
   expect(true).toBe(false);
});
peterjmag
  • 6,041
  • 1
  • 30
  • 27
flaky
  • 6,816
  • 4
  • 29
  • 46
  • 33
    Works for me with jest 20.0.4. Although it only skips the rest of the tests in that file. Tests in other files continue to run, unless you've already restricted the run to the one file. – Holf Sep 05 '17 at 15:35
  • 13
    That's a jest thing though - because it runs the tests asynchronously it probably can't determine which test to run in which file from the beginning. So it will run all files per default and WITHIN the files check for `test.only`. So if you only want to run one test within a file that has many test cases within a suite of testcases that consists of many files you have to unfortunately run that single file `jest myTestFile.test.js` – flaky Sep 06 '17 at 06:41
  • @johnslay: It does, just tested it – flaky Mar 13 '18 at 08:17
  • @flaky I guess i meant to say it does not work when running `npm test`. You will have to run the file by itself or press `p` to set a filter. – johnslay Mar 14 '18 at 20:28
  • 3
    @johnslay well, thanks for reading the previous comments before writing your response I guess /s :) – flaky Mar 15 '18 at 09:00
  • This will isolate in one file but it will still run the tests defined in other files as of `jest@24.9.0`, due to Jest running test files in parallel. You'd have to pass the test name to isolate from all, e.g. `npm test -- -t "sample test name" ` – demisx Dec 13 '19 at 16:38
  • Nice! Works in 24.9.0 – callback Dec 15 '19 at 19:31
  • One thing to note is that this appears be a regex field, so if you have a test case called like `'[foo] bar'`, you'll actually have to use the string `'\[foo] bar'`. – J.M. Janzen May 17 '21 at 14:27
  • 1
    Work with version 29.3.1 and it is very convenient with ts-jest + VsCode debugging. – Patrick Desjardins Dec 20 '22 at 23:36
203

Full command to run a single Jest test

Command:

node <path-to-jest> -i <your-test-file> -c <jest-config> -t "<test-block-name>"

  • <path-to-jest>:
    • Windows: node_modules\jest\bin\jest.js
    • Others: node_modules/.bin/jest
  • -i <you-test-file>: path to the file with tests (js or ts)
  • -c <jest-config>: path to a separate Jest config file (JSON), if you keep your Jest configuration in package.json, you don't have to specify this parameter (Jest will find it without your help)
  • -t <the-name-of-test-block>: actually it's a name (the first parameter) of describe(...), it(...), or test(...) block.

Example:

describe("math tests", () => {

  it("1 + 1 = 2", () => {
    expect(1 + 1).toBe(2);
  });

  it("-1 * -1 !== -1", () => {
    expect(-1 * -1).not.toBe(-1);
  });

});

So, the command

node node_modules/jest/bin/jest.js -i test/math-tests.js -c test/tests-config.json -t "1 + 1 = 2"

will test it("1 + 1 = 2", ...), but if you change the -t parameter to "math tests" then it will run both tests from the describe("math tests",...) block.

Remarks:

  1. For Windows, replace node_modules/.bin/jest with node_modules\jest\bin\jest.js.
  2. This approach allows you to debug the running script. To enable debugging add '--inspect-brk' parameter to the command.

Running a single Jest test via NPM scripts in 'package.json'

Having Jest installed, you can simplify the syntax of this command (above) by using NPM scripts. In "package.json" add a new script to the "scripts" section:

"scripts": {
  "test:math": "jest -i test/my-tests.js -t \"math tests\"",
}

In this case, we use an alias 'jest' instead of writing the full path to it. Also, we don't specify the configuration file path since we can place it in "package.json" as well and Jest will look into it by default. Now you can run the command:

npm run test:math

And the "math tests" block with two tests will be executed. Or, of course, you can specify one particular test by its name.

Another option would be to pull the <the-name-of-test-block> parameter outside the "test:math" script and pass it from the NPM command:

package.json:

"scripts": {
  "test:math": "jest -i test/my-tests.js -t",
}

Command:

npm run test:math "math tests"

Now you can manage the name of the run test(s) with a much shorter command.

Remarks:

  1. The 'jest' command will work with NPM scripts because

npm makes "./node_modules/.bin" the first entry in the PATH environment variable when running any lifecycle scripts, so this will work fine, even if your program is not globally installed (NPM blog) 2. This approach doesn't seem to allow debugging because Jest is run via its binary/CLI, not via node.


Running a selected Jest test in Visual Studio Code

If you are using Visual Studio Code you can take advantage of it and run the currently selected test (in the code editor) by pressing the F5 button. To do this, we will need to create a new launch configuration block in the ".vscode/launch.json" file. In that configuration, we will use predefined variables which are substituted with the appropriate (unfortunately not always) values when running. Of all available we are only interested in these:

  • ${relativeFile} - the current opened file relative to ${workspaceFolder}
  • ${selectedText} - the current selected text in the active file

But before writing out the launch configuration we should add the 'test' script in our 'package.json' (if we haven't done it yet).

File package.json:

"scripts": {
  "test": "jest"
}

Then we can use it in our launch configuration.

Launch configuration:

{
  "type": "node",
  "request": "launch",
  "name": "Run selected Jest test",
  "runtimeExecutable": "npm",
  "runtimeArgs": [
    "run-script",
    "test"
  ],
  "args": [
    "--",
    "-i",
    "${relativeFile}",
    "-t",
    "${selectedText}"
  ],
  "console": "integratedTerminal",
}

It actually does the same as the commands described earlier in this answer. Now that everything is ready, we can run any test we want without having to rewrite the command parameters manually.

Here's all you need to do:

  1. Select currently created launch config in the debug panel:

    Select launch config in the Visual Studio Code debug panel

  2. Open the file with tests in the code editor and select the name of the test you want to test (without quotation marks):

    Select test name

  3. Press F5 button.

And voilà!

Now to run any test you want. Just open it in the editor, select its name, and press F5.

Unfortunately, it won't be "voilà" on a Windows machines because they substitute (who knows why) the ${relativeFile} variable with the path having reversed slashes and Jest wouldn't understand such a path. (In case if the command needs troubleshooting, see similar approach in https://www.basefactor.com/using-visual-studio-code-to-debug-jest-based-unit-tests)

Remarks:

  1. To run under the debugger, don't forget to add the '--inspect-brk' parameter.
  2. In this configuration example, we don't have the Jest configuration parameter assuming that it's included in 'package.json'.
Rimian
  • 36,864
  • 16
  • 117
  • 117
Serg
  • 6,742
  • 4
  • 36
  • 54
  • 7
    Excellent! This should be the accepted answer. Especially if it adds a mention of `npx` to greatly simplify calling Jest, regardless of the OS. – Dan Dascalescu Mar 22 '19 at 05:53
  • Amazingly well explained answer. Probably jest documentation also doesn't have this good explanation :P – Shubham Jain Jul 06 '20 at 09:48
  • 2
    To be cross platform, use `${fileBasename}` instead of `${relativeFile}` in your launch configuration, because jest can't resolve path with backslash '\' (windows) – pchmn Nov 06 '20 at 11:57
  • Can this solution be made to work in Windows now that the Nov 2020 Update to VSCode has added the following new launch.json variables: ${fileWorkspaceFolder} - Resolves to the workspace folder path of the file open in the active VS Code editor. ${fileDirnameBasename} - Resolves to name of the folder that the file open in the active VS Code editor is in. ${pathSeparator} - Resolves to the character used by the operating system to separate components in file paths. – MartinDuo Dec 16 '20 at 18:49
  • For those using Windows, you can add a `"--runTestsByPath"` parameter to tell Jest to treat the `"${relativeFile}"` parameter as a plain path and not a RegEx so that the backslashes are parsed correctly. – Boric Feb 18 '22 at 16:08
66

As mentioned in other answers, test.only merely filters out other tests in the same file. So tests in other files would still run.

So to run a single test, there are two approaches:

  • Option 1: If your test name is unique, you can enter t while in watch mode and enter the name of the test you'd like to run.

  • Option 2:

    1. Hit p while in watch mode to enter a regex for the filename you'd like to run. (Relevant commands like this are displayed when you run Jest in watch mode).
    2. Change it to it.only on the test you'd like to run.

With either of the approaches above, Jest will only run the single test in the file you've specified.

Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61
Cory House
  • 14,235
  • 13
  • 70
  • 87
45

If you have jest running as a script command, something like npm test, you need to use the following command to make it work:

npm test -- -t "fix order test"
Mugur 'Bud' Chirica
  • 4,246
  • 1
  • 31
  • 34
  • 2
    If you have many test files, you should specify the name of the file too. e.g. `npm test -- testFile.js -t "fix order test"`. Otherwise it will go through all of the test files to find matches, which takes a lot longer. – mjuopperi Jun 22 '22 at 08:58
24

You can also use f or x to focus or exclude a test. For example

fit('only this test will run', () => {
   expect(true).toBe(false);
});

it('this test will not run', () => {
   expect(true).toBe(false);
});

xit('this test will be ignored', () => {
   expect(true).toBe(false);
});
Nima Soroush
  • 12,242
  • 4
  • 52
  • 53
  • 3
    `xit` did work for me, but `fit` does not. i am using jest@22.4.4. – Hinrich Aug 08 '18 at 12:09
  • 1
    I think that the main downside of this approach is that - if you're just trying to drill down on one test to fix a bug - it entails unnecessary changes to the underlying test files. If, for whatever reason, you want to maintain the test code (across commits, say) then this might make sense. – webelo Dec 20 '18 at 16:25
  • 1
    Also `fit` does not work for the same reason that `it.only` does not work. It only prevents other tests *in the same file* from running. Other files still run. – John Henckel Sep 03 '20 at 16:38
  • it.only And it.skip are more readable and less likely that you accidentally commit your temporary changes to source control – Michael Freidgeim Jul 02 '21 at 21:01
22

You can try using the following command cause it's working for me

npm run test -- -t 'Your test name'

Or the other way you can do is just add .only with your test like the following and run the command npm run test

it.only('Your test name', () => {})
Bablu Ahmed
  • 4,412
  • 5
  • 49
  • 64
17

As said a previous answer, you can run the command

jest -t 'fix-order-test'

If you have an it inside of a describe block, you have to run

jest -t '<describeString> <itString>'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
15

Use:

npm run test -- test-name

This will only work if your test specification name is unique.

The code above would reference a file with this name: test-name.component.spec.ts

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tony2tones
  • 1,422
  • 1
  • 18
  • 19
12

With the latest Jest version, you can use one of the following to only run one test, and the same for a test suite.

it.only('test 1', () => {})

test.only('test 1', () => {})

fit('test 1', () => {})

jest 'test 1' may work too if the test name is unique.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
schrodinger's code
  • 2,624
  • 1
  • 25
  • 19
11

On jest 26.6.0 this is the only thing that worked for me:

jest -- test/unit/name-of-test-file.test.ts

and to watch

jest --watch -- test/unit/name-of-test-file.test.ts

codeAline
  • 427
  • 1
  • 5
  • 9
10

In Visual Studio Code, this lets me run/debug only one Jest test, with breakpoints: Debugging tests in Visual Studio Code

My launch.json file has this inside:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Jest All",
      "program": "${workspaceFolder}/node_modules/.bin/jest",
      "args": ["--runInBand"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "windows": {
        "program": "${workspaceFolder}/node_modules/jest/bin/jest",
      }
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Jest Current File",
      "program": "${workspaceFolder}/node_modules/.bin/jest",
      "args": ["${relativeFile}"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "windows": {
        "program": "${workspaceFolder}/node_modules/jest/bin/jest",
      }
    }
  ]
}

And this in file package.json:

  "scripts": {
    "test": "jest"
  }
  • To run one test, in that test, change test (or it) to test.only (or it.only). To run one test suite (several tests), change describe to describe.only.
  • Set breakpoint(s) if you want.
  • In Visual Studio Code, go to Debug View (Shift + Cmd + D or Shift + Ctrl + D).
  • From the dropdown menu at top, pick Jest Current File.
  • Click the green arrow to run that test.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raymond Gan
  • 4,612
  • 3
  • 24
  • 19
  • In my case, your config runs only one test (with it.only(...)), but it doesn't stop at breakpoints :( – Tudor Leustean Oct 16 '18 at 07:38
  • Getting JavaScript to hit breakpoints in a debugger can be tricky, because of its asynchronous nature. In VS Code, play around with where you place your breakpoints, plus the commands in the Debug menu, till it hits them. If it keeps skipping breakpoints, place them EARLIER in your code. If 1 file calls a function in another file, place breakpoint at that function call, then "Step Into" the call to jump files. Play with these Debug commands: "Step Over, Step Into, Step Out, Continue" – Raymond Gan Oct 16 '18 at 13:31
  • 1
    Actually, you don't need `"scripts": { "test": "jest" }` in `package.json` because you have specified the full path in the `"program"` parameter in `launch.json` . – Serg Mar 15 '19 at 11:40
  • Thx, those `"${relativeFile}"` helped me to run single file in VSCode. – RAM237 Mar 17 '21 at 11:58
  • @TudorLeustean , probably worth mentioning, add `debugger;` on the line you want to stop, in my case setting breakpoints via UI didn't work for tests too. – RAM237 Mar 17 '21 at 12:01
7

For VSCode You can use jest-run-it extension that will help you run and debug Jest tests from your editor. enter image description here

Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
6

In the latest version of jest, you can run any single test in multiple ways.

fit('only this test will run', () => {});

it.only('only this test will run',() => {});
Raju Ahmed
  • 380
  • 5
  • 11
5

npm test __tests__/filename.test.ts - to run a single file.

test.only('check single test', () => { expect(true).toBe(true)}); - to run a single test case

test.skip('to skip testcase, () => {expect(false).toBe(false_}); - to skip a test case

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Swift
  • 829
  • 2
  • 12
  • 33
5

https://jestjs.io/docs/cli#--testnamepatternregex

Where your test is something like this file called my.test.js

test("My Sum", () => {
  const sum = 3;
  expect(sum).toBe(3);
});

Run on CLI with the test name

jest -t Sum

Use npm test with regex match part of file name example: my.test.js

npm test -t my
Anton Swanevelder
  • 1,025
  • 1
  • 14
  • 31
4

Here is my take:

./node_modules/.bin/jest --config test/jest-unit-config.json --runInBand src/components/OpenForm/OpenForm.spec.js -t 'show expanded'

Notes:

  • ./node_modules/.bin/... is a wonderful way, to access the locally installed Jest (or Mocha or...) binary that came with the locally installed package. (Yes, in your npm scripts you can jest with nothing before, but this is handy on command line... (that's also a good start for your debugging config, whichever IDE you are using...)
  • Your project might not have a set of configuration options. But if it does (peek into the scripts in package.json), this is, what you need.
  • --runInBand – as said, don't know about your configuration, but if you concentrate on developing/fixing a single test, you rather do not want to deal with web workers...
  • Yes, you can give the whole, explicit path to your file
  • Optionally, you can use -t to not run all tests in that file, but only a single one (here: the one, that has something with ‘show expanded’ in its name). Same effect can be achieved by glueing .only() into that file.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Frank N
  • 9,625
  • 4
  • 80
  • 110
4

Just a little add-on, because it seems there was kind of a fight if to use ./node_modules/.bin/jest -i ... or just jest -i ... or npm test -- -i ...

  1. Just calling jest works if you have it installed globally (as with npm install -g jest), a not-so-clean way of handling dependencies
  2. If you have Jest installed only locally in the package and want to call the Jest script without the npm script detour, you can use npx jest -i ... => this is exactly what npx is for. It saves you from writing ./node_modules/.bin/....
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
4

I took me a while to find this so I'd like to add it here for people like me who use yarn:

yarn test -i "src/components/folderX/folderY/.../Filename.ts" -t "name of test"

So filename after -i and testname after -t.

Tingolfin
  • 825
  • 8
  • 28
3

If anyone is trying to use jest -t '<testName>' and wondering why it isn't working, it's worth noting that -t argument is actually a regex pattern, not a string literal.

If your test name has no special characters in it then it will just work as expected (using either the string from it or describe or combinations of these).

If your test name does have special characters such as brackets, just escape them with a backslash. e.g. a test like:

it("/ (GET)", () => {
  return request(app.getHttpServer())
    .get("/health")
    .expect(200)
    .expect("Hello World");
});

Could be targeted with jest -t "\/ \(GET\)".

The regex doesn't need to match the entire string either, so you can match against common parts if you want to run a subset based on a consistent naming convention.

Tom Manterfield
  • 6,515
  • 6
  • 36
  • 52
2

There is now a nice Jest plugin for this called jest-watch-typeahead it makes this process much simpler.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rivanov
  • 1,214
  • 18
  • 19
2

The quickest/simplest way that I've found is with

npx jest TheNameOfYourFile

also, you can "subscribe" to keep reading changes with

npx jest TheNameOfYourFile --watchAll

CrsCaballero
  • 2,124
  • 1
  • 24
  • 31
2

The standalone -- is *nix magic for marking the end of options, meaning (for NPM) that everything after that is passed to the command being run. if you have 2 test file with these names: Sample-test1.js , Sample-test2.js and you just wish to run 1 of them, you should run this command.

npm test -- Sample-test1.js

which this part is static => nmp test --

and the second part is your test name file, like this => Sample-test1.js

aida
  • 43
  • 6
0

For VSCode in Windows, I use these in my launch.json file. Note the use of ${pathSeparator} to handle the difference in Win and Mac. Select one in the debug dropdown and press F5 to run.

 {
  "name": "Debug Selected Jest Test",
  "type": "node",
  "request": "launch",
  "runtimeArgs": ["--inspect-brk", "${workspaceRoot}/node_modules/jest/bin/jest.js", "--runInBand"],
  "args": ["--", "-i", "${fileDirnameBasename}${pathSeparator}${fileBasename} ", "-t", "${selectedText}"],
  "console": "integratedTerminal",
  "internalConsoleOptions": "neverOpen",
  "port": 9229
},
{
  "name": "Debug Named Jest Test",
  "type": "node",
  "request": "launch",
  "runtimeArgs": ["--inspect-brk", "${workspaceRoot}/node_modules/jest/bin/jest.js", "--runInBand"],
  "args": ["--", "-i", "${fileDirnameBasename}${pathSeparator}${fileBasename} ", "-t", "filename.test.js"],
  "console": "integratedTerminal",
  "internalConsoleOptions": "neverOpen",
  "port": 9229
},
MartinDuo
  • 663
  • 12
  • 25
0

run this command line :

   npm run test-jest unit_test/file_name -- -t test_name

My Package.json

"test-jest": "jest --verbose=true --force-exit",
"test-jest:watch": "jest --watchAll",
mubasshir00
  • 307
  • 3
  • 9
0

After checking the Jest CLI doc, I found this is how we run a specific test in a specific file.

jest --findRelatedTests path/to/fileA.js path/to/fileB.js -t "test name"

With yarn,

yarn test --findRelatedTests path/to/fileA.js path/to/fileB.js -t "test name"

With npm,

npm test -- --findRelatedTests path/to/fileA.js path/to/fileB.js -t "test name"

For reference please check Jest Cli Options

Yehya
  • 506
  • 1
  • 5
  • 16