508
votes

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'

25

25 Answers

502
votes

Since at least 2019:

npm test -- SomeTestFileToRun

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.

453
votes

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
49
votes

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.

29
votes

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",
    ...
  },

}
26
votes

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 is what worked for me, at the root level of the project:

node_modules/.bin/jest [args]

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

21
votes

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

npm test -- fileName.jsx 
17
votes

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.

8
votes

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.

7
votes

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"
  • 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
4
votes

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.

4
votes

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

4
votes

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]
3
votes

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.

3
votes

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");
  })
})
2
votes

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

2
votes

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
1
votes

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.

1
votes

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
1
votes

From the Jest documentation:

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

Run this with

 npm run test
1
votes

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.

1
votes

If you dont want to install jest globally you can use

npx jest foo.test.js
0
votes

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)

0
votes
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'
0
votes

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"
  }
}
-1
votes

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