Table of Contents

About

Javascript Test with Jest in IDEA

Structure

  • Source File: auth.js
  • Test File: auth.test.js. Go to test file from source file: Ctrl+Shift+T or Navigate > Test

The test file:

  • name should have a .test., .spec. or _spec. suffix
  • location should be either next to the source file or in a test folder.

Steps

Install the node plugin

Jest is a node process, the node plugin must be installed. See node plugin

Javascript Language

Jest use es6 language:

Intellij Javascript Version Es6

Install jest

Run configuration

To get run configuration automatically and as gutter, you can add the rc-producer.yml run configuration file.

Add the file rc-producer.yml to the subdirectory ./idea - rc means run configuration. See this file for the meaning of each property.

- &defaults
  files: ["**/__tests__/**/*", "**/*.spec.*", "**/*.test.*", "!**/node_modules/**/*"]
  
  script: "node_modules/jest/bin/jest.js"
  scriptArgs: ["-i", &filePattern '--testPathPattern=[/\\]{1}${fileNameWithoutExt}\.\w+$']
  rcName: "${fileNameWithoutExt}"

-
  <<: *defaults
  lineRegExp: '^\s*(?:test|it|describe)(?:\.[^(]+)?\((?:"|''){1}([^"'']+)'
  scriptArgs: ["-i", "-t", "${0regExp}", *filePattern]
  rcName: "${fileNameWithoutExt}.${0}"

Add jest as global library

Jest doesn't use any import statement and therefore the syntax checking may report an Missing import statement. To avoid it, you need to install the Jest typescript declaration

  • File Settings (Ctrl+Alt+S)
  • And…

Jest As Global Library Intellij

Then, the errors will disappear but you get also a little bit of completion.

Jest Completion Idea

Create a test in the test directory:

test('adds 1 + 2 to equal 3', () => {
    expect(1 + 2).toBe(3);
});

Configure it

By default, jest is looking in all directory to search for test files. This takes a lot of time. You can restrain this behavior by adding properties in the package.json file

{
  ...............
  "jest": {
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "roots": ["<rootDir>/test/"]
  },
  ...............
}

Run it

  • You can then run a test from everywhere.
    • Click the left gutter. Choose Run <test_name> or Debug <test_name> from the pop-up list.
    • Run/Debug Configuration
    • Ctrl + Enter when on the test function name
    • Right+Click on the file + Run

Idea Jest Run

C:\Users\gerard\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\172.3757.52\bin\runnerw.exe 
D:\nodejs\node.exe D:\myProject\node_modules\jest\bin\jest.js -i --testPathPattern=[/\\]{1}base.test\.\w+$
PASS  test\base.test.js
  √ adds 1 + 2 to equal 3 (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.03s
Ran all test suites matching /[\/\\]{1}base.test\.\w+$/i.

Documentation / Reference