817

I am able to test multiple files using Jest, but I cannot figure out how to test a single file.

I have:

  • Run npm install jest-cli --save-dev
  • Updated package.json: `{ ... "scripts": { "test": "jest" } ... }
  • Written a number of tests.

Running npm test works as expected (currently it runs 14 tests).

How do I test a single file, e.g. test app/foo/__tests__/bar.spec.js?

I have tried running npm test app/foo/__tests__/bar.spec.js (from the project root), but I get the following error:

npm ERR! Error: ENOENT, open '/node_modules/app/foo/tests/bar.spec.js/package.json'

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Musket
  • 8,585
  • 2
  • 16
  • 9
  • 1
    Use `npx jest Foo.test.js` use `--watchAll` if you want to watch changes in the background e.g `npx jest --watchAll Foo.test.js` – Shiran Gabriel Jul 22 '21 at 12:34
  • And for watching, can also pass like this: `npm test -- bar.spec.js --watchAll` / `yarn test -- bar.spec.js --watchAll`. – Steve Harrison Feb 01 '23 at 08:30
  • No one worked for me. Check my workaround https://stackoverflow.com/a/75404447/3957754 for linux users – JRichardsz Feb 09 '23 at 21:12
  • No one worked for me. Check my workaround for linux users https://stackoverflow.com/a/75404447/3957754 – JRichardsz Feb 09 '23 at 21:15
  • in latest versions of jest you could use `it.only()`, `describe.only()`, etc in which case it will just execute that single test without having to pass a file or filter parameter. – cancerbero May 08 '23 at 13:57

34 Answers34

917

Since at least 2019:

npm test -- bar.spec.js

In 2015:

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.spec.js.

Note: You don't have to enter the full path to your test file. The argument is interpreted as a regular expression. Any part of the full path that uniquely identifies a file suffices.

icc97
  • 11,395
  • 8
  • 76
  • 90
ncuillery
  • 14,308
  • 2
  • 22
  • 31
  • 9
    Unfortunately this isn't working for me. Running `jest bar.spec.js` gives `jest: command not found`. I've confirmed Jest is installed (`npm list -g jest` shows `jest@0.1.37`). FWIW, when I run using `npm test` it uses `jest-cli`. – Musket Feb 26 '15 at 13:42
  • 7
    Yes, `jest-cli` is the right module, install it globally `npm install -g jest-cli`. `jest` in npm is... [something else](https://www.npmjs.com/package/jest) – ncuillery Feb 26 '15 at 17:24
  • Thank you. Installing `jest-cli` globally allowed me to run `jest bar.spec.js`. – Musket Feb 27 '15 at 00:30
  • 64
    That's incorrect. npm test working does not mean that jest is installed globally. It just means jest is installed within your project. – Chiedo May 22 '15 at 20:00
  • 31
    Like @ChiedoJohn said. To run it without installing globally, you can run this from the root of your app: `node_modules/.bin/jest args` – Eddie Monge Jr Sep 15 '15 at 22:09
  • is there any alternative method for running jest tests apart from command line?? , as if i make post request to my existing project rest api's its will give me CSRF token problem. – Suyog Sawant Oct 30 '15 at 10:49
  • 2
    It is ridiculously hard to run a single test file because of the regex file search. I always end up renaming the file that I need to test to something like: `bar.specTEST.js` and then run `npm test bar.specTEST.js`. And renaming back when I am done – mlunoe Mar 03 '16 at 19:23
  • 5
    If you're using the default jasmine setup you can focus a single test by using `fit` instead of `it`. – eremzeit Apr 13 '16 at 22:42
  • 1
    @eremzeit That's useful, but only applies if you have a single test file. It will still run other test files that match the test pattern. – Joshua Pinter Nov 11 '17 at 19:00
  • 3
    With the advent of npx, you can run `npx jest bar.spec.js` instead of installing jest globally. It will also read the jest version from your devDependencies – David R. Sep 12 '18 at 17:56
  • this is not the best answer. Check out the answers of @cabaji99 and Nicholas Carey for better options – Cpt. Senkfuss Apr 19 '19 at 13:56
  • And how do we run code coverage just for a single test in Jest? – darKnight Sep 09 '19 at 18:41
  • 2
    You can use `npm test` like `npm test -- bar.spec.js` – nrofis Nov 20 '19 at 10:02
  • 2
    I was able to run it by doing ```yarn jest FILE``` – Chris Habgood Mar 27 '20 at 21:19
  • Thank you! npm test -- filename works great and is saving me so much time now. Best answer – Micah Nov 09 '22 at 16:27
544

All you have to do is chant the magic incantation:

npm test -- SomeTestFileToRun

The stand-alone -- is *nix magic for marking the end of options, meaning (for NPM) that everything after that is passed to the command being run, in this case jest. As an aside, you can display Jest usage notes by saying

npm test -- --help

Anyhow, chanting

npm test -- Foo

runs the tests in the named file (FooBar.js). You should note, though, that:

  • Jest treats the name as case-sensitive, so if you're using a case-insensitive, but case-preserving file system (like Windows NTFS), you might encounter what appears to be oddness going on.

  • Jest appears to treat the specification as a prefix.

So the above incantation will

  • Run FooBar.js, Foo.js and FooZilla.js
  • But not run foo.js
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • Thanks, unfortunately I get the same error when running this: `npm ERR! Error: ENOENT, open '/node_modules//package.json'` – Musket Mar 02 '15 at 20:23
  • 2
    is there any alternative method for running jest tests apart from command line?? , as if i make post request to my existing project rest api's its will give me CSRF token problem. As how will i setup jest testing to my existing project ?? so that it will start serving request using '/rest-api' instead of 'http://localhost:8000/rest-api' – Suyog Sawant Oct 30 '15 at 10:51
  • 2
    @SuyogSawant: that's not a comment. it's a question on its own. You should should ask it here on StackOverflow. – Nicholas Carey Oct 30 '15 at 20:44
  • 3
    in my case simple `npm test ToDoForm.test.js` worked while `jest ToDoForm.test.js` didn't – Tomasz Mularczyk Jan 21 '17 at 17:10
  • your second point about case sensitivity does not match the incantation you provide above. – NSjonas Nov 22 '17 at 18:11
  • 2
    For windows you will need to type double backslashes for the file path. Ex: yarn run test src\\tests\\actions\\auth.test.js – Kermit Mar 28 '20 at 17:54
  • Worked like a charm! – artfulbeest Jul 04 '20 at 06:05
84

If you install the Visual Studio Code plugin Jest Runner,

Enter image description here

You will have Debug/Run options above every describe and it.

Enter image description here

You can open your test file in Visual Studio Code and click on one of those options.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nPcomp
  • 8,637
  • 2
  • 54
  • 49
  • 3
    Jest Runner did not work for me in some test cases, Then I switched to Jest extension for VSCode and it worked for me. https://marketplace.visualstudio.com/items?itemName=Orta.vscode-jest – Asanka Siriwardena Aug 10 '22 at 06:54
61

To run an individual test:

npm test -t ValidationUtil # `ValidationUtil` is my module `ValidationUtil.spec.js`

-t - after it, put a regular expression containing the test name.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cabaji99
  • 1,305
  • 11
  • 9
57

Using npm test doesn't mean Jest is installed globally. It just means "test" is mapped to using Jest in your package.json file.

The following works, at the root level of the project:

npx jest [file or directory]

file or directory can be the test file you want to run or the directory containing multiple files.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
AeroHil
  • 937
  • 8
  • 5
  • 11
    a shortcut to execute binaries in `node_modules/.bin` is to use `npx` command. For instance `npx jest [args]` – Sergio Mazzoleni Jan 18 '19 at 16:09
  • 1
    worth pointing out that @Aerohil didn't miss that; the command did not exist in 2016; I updated the answer – jcollum Oct 14 '21 at 23:55
  • This one is the only one that worked for me. All the other flavours, using npm, ran ALL tests, despite output saying that a regex was applied, and seemed restrictive... Also, you may just run `npx jest `, even if your file lies within subfolders inside of tests. – Fabien Haddadi Apr 03 '23 at 20:41
55

If you use Yarn, you can add the .spec.js or .test.js file directly after:

yarn test src/lib/myfile.test.js

This is the part from my package.json file with Jest installed as a local package (removed the relevant parts):

{
...
  "scripts": {
    "test": "jest",
    "testw": "jest --watch",
    "testc": "jest --coverage",
...
  },
  "devDependencies": {
    "jest": "^18.1.0",
    ...
  },

}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • You can also use `yarn test SomeRegexHere` to save typing, e.g. `yarn test MyClass`. However, note that as of Dec 4, 2021, the regex matches against the absolute path, so your pattern may match folder names that contain your source tree. See https://github.com/facebook/jest/issues/8226 – vaughnkoch Dec 04 '21 at 18:59
26

You could use the file name with npm test --:

npm test -- fileName.jsx 
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Hilal Aissani
  • 709
  • 8
  • 3
16

We are using nrwl-nx with Angular. In this case we can use this command:

npm test <ng-project> -- --testFile "file-name-part"

Notes:

  • npm test will run the test script specified in package.json: "test": "ng test"
  • --: tells npm to pass the following parameters to the test script (instead of consuming them)
  • Thus the rest of the cmd will be passed to ng test
    • <ng-project> is the name of a project in angular.json
      • when you omit this parameter, the "defaultProject" (specified in angular.json) will be used (so you must specify it, when the test is not in your default project)
    • Next we must check which builder is used:
      • In angular.json navigate to "project" - "<ng-project>" - "architect" - "test"
      • and check the "builder", which in our case is: "@nrwl/jest:jest"
    • Now that we know the builder, we need to find the available cmd-line parameters
      • On the command line, run npm test <ng-project> -- --help to see all available options
      • Or check the online documentation
    • One of the options is --testFile which is used here
TmTron
  • 17,012
  • 10
  • 94
  • 142
12

With a package.json script

With "scripts": { "test": "jest" } in package.json:

npm test -- foo/__tests__/bar.spec.js

Using jest-cli directly

Globally-installed:

jest foo/__tests__/bar.spec.js

Locally-installed:

./node_modules/.bin/jest foo/__tests__/bar.spec.js

Using --testPathPattern

The --testPathPattern option has the equivalent effect of passing paths as unnamed positional arguments to jest-cli. See normalize.ts.

./node_modules/.bin/jest --testPathPattern foo/__tests__/bar.spec.js

Testing two or more specific files

Separate filenames with commas or spaces:

./node_modules/.bin/jest foo/__tests__/bar.spec.js,foo/__tests__/foo.spec.js
./node_modules/.bin/jest foo/__tests__/bar.spec.js foo/__tests__/foo.spec.js

Pass --testPathPattern multiple times:

./node_modules/.bin/jest --testPathPattern foo/__tests__/bar.spec.js --testPathPattern foo/__tests__/foo.spec.js
Spencer
  • 1,161
  • 12
  • 19
11

To run a specific test in a specific file:

yarn test -f "partial-filename" -t "as split node"

npm test, or jest can replace yarn test, depending on your preferred JS bundler.

This would only attempt to find tests in files that contained some-partial-filename, and within those files, the test would need to have a describe or it directive that mentions "as split node", for example

// In cool-partial-filename.js
describe("with a less indented sibling", () => {
  it("should create a new check-list-item with the same indent as split node", () => {
    console.log("This would run with the invocation above");
  })
})
wbharding
  • 4,213
  • 2
  • 30
  • 25
8

If you are running npm >= 5.2.0 and you have installed Jest locally as a devDependencies with npm i -d jest, you can run Jest on a particular file by doing npx jest /path/to/your/spec.js.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bmaggi
  • 2,908
  • 1
  • 19
  • 16
8

Use this command:

npx jest test --runTestsByPath <path-to-file>
Natan Farkash
  • 256
  • 3
  • 4
7

At that time, I did it by using:

yarn test TestFileName.spec.js

You shouldn't put in the complete path. That works for me on a Windows 10 machine.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
6

It can also be achieved by:

jest --findRelatedTests path/to/fileA.js

Reference (Jest CLI Options)

How can that be achieved in the Nx monorepo? Here is the answer (in directory /path/to/workspace):

npx nx test api --findRelatedTests=apps/api/src/app/mytest.spec.ts

Reference & more information: How to test a single Jest test file in Nx #6

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sohel Ahmed Mesaniya
  • 3,344
  • 1
  • 23
  • 29
6

If you dont want to install jest globally you can use

npx jest foo.test.js
king_leo
  • 107
  • 2
  • 4
5

This is how I dynamically run tests on a specific file without restarting the test.

My React project was created as create-react-app.

So it watches test for changes, automatically running test when I make changes.

So this is what I see at the end of the test results in the terminal:

Test Suites: 16 passed, 16 total
Tests:       98 passed, 98 total
Snapshots:   0 total
Time:        5.048s
Ran all test suites.

Watch Usage: Press w to show more.

Press W

Watch Usage
 › Press f to run only failed tests.
 › Press o to only run tests related to changed files.
 › Press q to quit watch mode.
 › Press p to filter by a filename regex pattern.
 › Press t to filter by a test name regex pattern.
 › Press Enter to trigger a test run.

Then press P

Pattern Mode Usage
 › Press Esc to exit pattern mode.
 › Press Enter to filter by a filenames regex pattern.

 pattern ›

 Start typing to filter by a filename regex pattern.

This is after I wanted to run the 'index.es6.js' file in the 'Login' folder:

Pattern Mode Usage
 › Press Esc to exit pattern mode.
 › Press Enter to filter by a filenames regex pattern.

 pattern › login/index

 Pattern matches 1 file
 › src/containers/Login/index.es6.test.js

That's how I run tests on a specific file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
deko
  • 161
  • 1
  • 2
  • 8
5

The simple way is to run a single unit test file, is inside the root folder run the command in the terminal.

npm test <fileName.test.js>

// For example
npm test utils.test.js

I have also tried the Jest Runner Extensions for Visual Studio Code, and it works great.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Siddharth Sunchu
  • 866
  • 10
  • 13
5

Jest and Jest Runner are super useful VSCode extensions when you working on jest.

Jest An automatic test runner

Jest Runner Adds "Run | Debug" code lens above the test to run or debug a single test.

"Run | Debug" code lens

Jack Steam
  • 4,500
  • 1
  • 24
  • 39
Him Ho
  • 79
  • 1
  • 6
  • Link-only responses are fine as a Comment, but are unacceptable as answers. Answers must be self contained, and exact code necessary to solve the issue must be embedded. Links are perfectly acceptable, BUT relevant info from the link must be embedded. No-one wants to click on blind links, and, importantly, your response becomes useless if the site becomes unreachable, or the content changes. – Tyler2P Aug 13 '21 at 12:05
5

The below command worked for me.
npx jest -i file-name

No need to specify complete path of the file, filename is sufficient.

Edit : Found another way to do it.
npm run test:functional -i file-name for Functional Test
npm run test:integration -i file-name for Integration Test

4

A simple solution that works:

yarn test -g fileName or

npm test -g fileName

Example:

yarn test -g cancelTransaction or

npm test -g cancelTransaction

More about test filters:

Test Filters
--fgrep, -f Only run tests containing this string [string]
--grep, -g Only run tests matching this string or regexp [string]
--invert, -i Inverts --grep and --fgrep matches [boolean]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gabriel Arghire
  • 1,992
  • 1
  • 21
  • 34
4

Do this if you are using yarn

yarn test nameofthefile

eg:

yarn test file.test.js
Byusa
  • 2,279
  • 1
  • 16
  • 21
3

There isn't any need to pass the full path. Just use a regular expression pattern.

See --testLocationInResults.

yarn jest --testNamePattern my_test_name
yarn jest -t=auth
yarn jest -t component # This will test all whose test name contains `component`

yarn jest --testPathPattern filename # This will match the file path
yarn jest filename # This will match the file path, the same with above
W.Perrin
  • 4,217
  • 32
  • 31
2

I just installed Jest as global, ran jest myFileToTest.spec.js, and it worked.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
URL87
  • 10,667
  • 35
  • 107
  • 174
2

Just use this command to run and check the coverage of the particular file.

yarn run test Index.js -u --coverage --watchAll=false
Manik Kumar
  • 764
  • 7
  • 17
2

For example on ReactJs Project, I installled Jest-cli globally by this command

npm i -g jest-cli

then in the root folder in my project, I can use this command to run the test for this single file <<Todo.test.js>>

jest Todo.test.js

It is working fine from my end. I hope it will working from our also.

Confiance
  • 706
  • 5
  • 7
1

You have two options:

  • Option 1: Command line. You can run the following command

    node '/Users/complete-path-to-you-project/your-project/node_modules/.bin/jest' '/Users/complete-path-to-you-project/your-project/path-to-your-file-within-the-project/your-file.spec.ts'
    

    This avoids you to install Jest globally. You use the jest used by your project.

  • Option 2: If you are using Visual Studio Code you have a great plugin to do this: Jest Runner. It allows you not only to run tests file by file, but even specific suites and specs just by a right click on the tests you want to run.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hay OUE
  • 44
  • 1
  • 5
1

With Angular and Jest you can add this to file package.json under "scripts":

"test:debug": "node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand"

Then to run a unit test for a specific file you can write this command in your terminal

npm run test:debug modules/myModule/someTest.spec.ts
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Photonic
  • 1,316
  • 19
  • 31
1

From the Jest documentation:

  "scripts": {
    "test": "jest path/to/my-test.js"
  }

Run this with

 npm run test
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shahrear Bin Amin
  • 1,075
  • 13
  • 31
1

With a package.json:

  "scripts": {
    "test": "jest --coverage",
    "start": "node index.js"
  }

The following worked for me:

npm test -f comm -- -t=first

It will find all files containing 'comm' in its filename and only run tests containing 'first' in the found files.

dunerztd
  • 11
  • 1
0

Jest will use what you pass as a regular expression pattern. That it will match for.

If you want to run a specific test file, then the best way to do it is to use the precise full path to it. (You can too specify a certain relative path like (src/XFolder/index.spec.ts)).

The easiest way to provide the full path being in the directory and in Linux is:

jest $PWD/index.spec.ts

Note the use of the variable $PWD.

Enter image description here

For Windows! (to be updated)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohamed Allal
  • 17,920
  • 5
  • 94
  • 97
0
import LoggerService from '../LoggerService ';

describe('Method called****', () => {
  it('00000000', () => {
    const logEvent = jest.spyOn(LoggerService, 'logEvent');
    expect(logEvent).toBeDefined();
  });
});

Usage:

npm test -- __tests__/LoggerService.test.ts -t '00000000'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Swift
  • 829
  • 2
  • 12
  • 33
  • An explanation would be in order. E.g., what is it supposed to achieve and is the first part the content of file *LoggerService.test.ts*? – Peter Mortensen Sep 24 '20 at 21:03
0

For NestJS users, the simple alternative is to use,

npm test -t <name of the spec file to run>

NestJS comes preconfigured with the regex of the test files to search for in case of Jest.

A simple example is -

npm test -t app-util.spec.ts

(that is my .spec file name)

The complete path need not be given since Jest searches for .spec files based on the configuration which is available by default in case of NestJS:

"jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vijayakumarpsg587
  • 1,079
  • 3
  • 22
  • 39
0

enter image description here

if you want to see a complete report like this with coverage by file and without the global coverage you can setup your environment the next way, this is a single test file but with super powers

package.json

"scripts": {
    "cov": "npm run test \"$src\" -- --coverage --collectCoverageFrom=\"$(echo $src | sed 's/.spec//')\"",
},

jest.config.js

{
    coverageReporters: ['lcov', 'text-summary']
}

Usage:

#  src=your_path_file npm run cov
$  src=src/components/Footer/Footer.spec.tsx npm run cov
-2

"test": "jest api/ds_server/ds_server.test.js"

Royer Adames
  • 868
  • 9
  • 13