Testing with Jest in WebStorm

Jest, the testing platform developed by Facebook, is becoming more and more popular with each day, especially for testing React applications. Jest is fast, easy to get started with, and has lots of features (such as snapshot testing and test coverage) available out of the box.

In WebStorm we wanted to streamline the whole testing workflow and make writing, running, and debugging tests with Jest even smoother and easier. Let’s see how WebStorm can help you test your app with Jest.

As an example, we’ll use the react-dropzone project that uses Jest and Enzyme. Enzyme helps you manipulate your React components while testing.

We won’t go into the details of installing and setting up Jest in a project. For that, we recommend Jest’s official documentation and this blog post on testing React apps.

Configure code completion

You might have noticed that some of the global Jest methods (like describe and beforeEach) in JavaScript files are marked as unresolved in the editor. To fix that, install the TypeScript type definition files for Jest: Go to Preferences | Languages & Frameworks | JavaScript | Libraries, click Download on the right-hand side of the dialog, then search for Jest in the list and click Install. Or add @types/jest to devDependencies in project’s package.json.

JavaScript libraries configuration dialog in WebStorm

This happens because Jest defines these methods in the global scope – so you don’t need to import them in each test file. But it also makes it harder for WebStorm to learn about them from the static analysis of the Jest sources – that’s why they are marked by default as unresolved.

Run tests

Create a run configuration to run all tests in the project
First, let’s run all the tests we have in our project. We need to create a run/debug configuration:

  • in the menu Run, select Edit configurations
  • then click + and select Jest from the drop-down list

Usually, you don’t have to change anything in the configuration, but if there’s a Jest configuration file in the project or you need to pass additional flags to Jest, you should do so in this configuration.

Run debug configuration for running all Jest tests

For now, we will just select All tests at the bottom of the dialog and click OK to save the configuration. You will immediately see the new configuration at the top right corner of the IDE – now click the green icon next to it to run it.

Run configuration from the IDE toolbar

View test results

In the test tool window that opens, you can track the test progress and see all the test results (you can also see the test result in the editor, right next to the test). All the tests will be listed in a tree view on the left side of the tool window. On the right, you will see a stack trace for the tests that failed.

Test results in the tool window

Double-click the test name in the list to open it in the editor. In WebStorm 2018.3, for failed tests, it will open the line that was at the top of the stack trace.

Use the icons at the top of the tool window to hide all the passed and ignored tests from the results.

Show only failed tests

If you want to find a particular test in the test results, just start typing its name and then use the up and down arrows to jump between the matched test names.

Quick search in the test tool window

Run a single test, test suite, or file

If you have lots of tests and you only want to run some of them, you have a bunch of options available.

In the editor, next to each test and test suite you can see an icon – it shows the test status for the tests that you have recently run. If you click it, you can select whether you want to run or debug this particular test or suite.

Run or debug a single test

This way, we can very quickly run or debug a test – there is no need to create a new run/debug configuration yourself. WebStorm will use the template for the new Jest run configuration that can be modified in the menu Run | Edit configurations – Default configurations – Jest.

If you want to run the whole test file with Jest, right-click it and select Run.

Run or debug a test file

Rerun only failed tests

If you have implemented a fix for the failed tests and now want to rerun them to check the fix, click the Rerun failed tests button in the tool window.

Rerun only failed tests

Run tests in watch mode

One of the greatest features that Jest has is a watch mode for running tests. In this mode, once you’ve made changes to the test or related files, the tests will be restarted automatically. By default, WebStorm doesn’t enable the watch mode when running all tests, but it’s very easy to enable it.

Open the Jest run/debug configuration that we created earlier and add --watchAll to the Jest options field, save the configuration, and then run it again.

Now, if you fix our failing test or add a new test and save the changes, Jest will rerun the tests and you will see the new results in the test tool window.

Running Jest tests in watch mode

This is particularly handy if you’re doing test-driven development and you first develop the tests and then add the feature they cover – you will see how your tests turn from red to green in the test view without having to restart them every time.

By the way, you can quickly jump from the file to its test file and back using the shortcut Cmd-Shift-T / Ctrl-Shift-T. This navigation works if the files follow one of the popular naming conventions (e.g. are named app.js and app.spec.js or app.test.js).

Note that the individual tests started from the editor will not be run in the watch mode until you add --watch to the template for the Jest configuration.

Snapshot testing

Another feature provided by Jest is snapshot testing. Snapshot files describe the DOM elements in a special format, so your tests can check the UI against these snapshots and the IDE will warn you if the UI component changes unexpectedly.

The first time you run the test that has a .toMatchSnapshot() method, Jest creates a snapshot file in the __snapshots__ folder. You can jump from the test to the related snapshot by clicking the camera icon next to it:

Go to snapshot

Then, if the tested component has changed and it no longer matches the snapshot, the test will fail.

To make it easier to spot the difference between the actual and expected results, we’ve added a diff view for snapshots. Click the link in the test output next to the stack trace to see the diff.

Diff view for Jest snapshots

If the change was actually intentional, you can update the snapshot by clicking another link in the tool window:

Update snapshot

Debug tests

To investigate why a test is failing, you can debug it in WebStorm. Click the gutter icon next to the test in the editor, and then select Debug

to debug just one test. Alternatively, click the green debug icon next to the All tests configuration that we created earlier.

The breakpoint can be set either in the test file or in the source code that is tested. Once the breakpoint is hit, you can step through the code, see the call stack and variables, use the console, and so on.

Debug Jest tests

When using Jest with JavaScript and the babel-jest package, the inline source maps that are needed for debugging should work out of the box. If using them with TypeScript, don’t forget to add these options to your tsconfig.json: "sourceMap": true, and "inlineSourceMap": true.

Test coverage

To make sure that all your source code is well tested, you can build a code coverage report. All you need to do is to click the ‘Run with coverage’ button next to the run/debug configuration. The report will show how many files were covered with tests and what percentage of lines in those files are covered.

Run tests with coverage

From this report, you can jump to the file and see which lines were covered (marked green) and which ones were not (marked red).

Tes coverage report

That’s it! We hope you find this guide useful and have a great experience testing with Jest in WebStorm. If you run into any problems or would like to share your suggestions, feel free to submit an issue in our tracker.

Your WebStorm Team

About Ekaterina Prigara

Ekaterina Prigara is WebStorm product marketing manager at JetBrains. She's passionate about new technologies, UX and coffee.
This entry was posted in Tutorials and tagged , , , . Bookmark the permalink.

17 Responses to Testing with Jest in WebStorm

  1. Kyle says:

    Is there any way to create a test file when one isn’t found such as documented here:

    https://www.jetbrains.com/help/idea/2017.3/creating-tests.html#d102209e7

    Thanks!

  2. Great to see how Webstorm makes it easier to work with Jest!

    I want to ask something not directly relevant to the article, but relevant to the blog as a whole. I see there are no meta tags for blog posts and that makes it a bit harder to share articles on twitter. Something like https://developer.twitter.com/en/docs/tweets/optimize-with-cards/guides/getting-started.html can be very helpful and I’m sure will benefit jetbrains products as well as people like me who want to share articles ;)

  3. Stephen O says:

    Hi,

    It seems that the latest release of vue-cli 3 has broken Webstorm Jest integration. When running tests I get the following error.

    “C:\Program Files\JetBrains\WebStorm 2018.2.4\bin\runnerw.exe” “C:\Program Files\nodejs\node.exe” C:\dev\package-test\vue-msal\tests\unit\plugin\VueMSAL\AzureAuthService.spec.js
    C:\dev\package-test\vue-msal\tests\unit\plugin\VueMSAL\AzureAuthService.spec.js:1
    (function (exports, require, module, __filename, __dirname) { import AzureAuthService from ‘@/plugin/VueMSAL/AzureAuthService’
    ^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected identifier
    at new Script (vm.js:73:7)
    at createScript (vm.js:245:10)
    at Object.runInThisContext (vm.js:297:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:266:19)

    The debug plugin @vue/cli-plugin-unit-jest says:

    “Note that directly running jest will fail because the Babel preset requires hints to make your code work in Node.js, so you must run your tests with vue-cli-service test:unit.”

    Any suggestions how to get the Jest integration working again?

    • lena_spb says:

      Hello!

      looks as if you are using Node.js run configuration to run your specs, passing test files directly to Node.js instead of using Jest test runner. Please make sure to use Jest run configuration

  4. Artem says:

    Unfortunately all that didn’t work for my project.
    I have added @types/jest to the libraries, tried to add index.d.ts directly from jest node modules. Nothing worked for me..
    I am still having compiling issues in the WebStorm “Cannot find name ‘jest'”

    in VS Code everything works fine, but in WebStorm not. So disapoiting :(

    • Ekaterina Prigara says:

      Can you please provide a bit more information about the problem? What exactly doesn’t work for you? Where do you see this compilation error? Do you use Jest with TypeScript?

  5. Demian says:

    Hi,

    Thanks for the blog, excellent work!

    Regarding “The breakpoint can be set either in the test file or in the source code that is tested”, I find that I can stop in the testcode (foo.spec.ts) no problem but not on the code under test (foo.ts). Furthermore a stacktrace of an error would be like

    “at Function. (../src/foo/foo.ts:6088:64)” but foo.ts has only ~400 lines!

  6. John says:

    Hi Ekaterina. First of all, thank you for the nice article!

    I have been testing with Webstorm and JEST for a while now. Today, I realized that there is a ‘Go to test’ option in Webstorm (Right Click in the editor -> Go to -> Test), which could be a very convenient feature for me. However, this menu option does not really go anywhere, as I never specified any explicit link between a test and the method it tests (imagining this is possible somehow), and Webstorm does not seem to do anything automatic about this either.

    I checked the JEST pages of Jetbrains for a way to link my tests to the methods/classes they test, but I had no luck. Do you think you could point me in the right direction?

    • Ekaterina Prigara says:

      Hello John,
      At the moment WebStorm matches source files with test files based on the file name. It supports some common patterns, e.g from App.js you will be able to jump to a test file called App.test.js or App.spec.js. It also works when tests are located in the folder called test or __tests__.
      These patterns are not configurable. Please vote for this feature request if you want to be able to configure them: https://youtrack.jetbrains.com/issue/WEB-29053

      Where are tests located in your project and how are they named?

  7. Felix says:

    What About:

    [error] Error: Could not find the implementation for builder @angular-builders/jest:run
    at WorkspaceNodeModulesArchitectHost.resolveBuilder (C:\XXXX\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js:49:19)
    at TestCommand.initialize (C:\XXXX\node_modules\@angular\cli\models\architect-command.js:134:55)
    at async TestCommand.validateAndRun (C:\XXXX\node_modules\@angular\cli\models\command.js:124:9)
    at async Object.runCommand (C:\XXXX\node_modules\@angular\cli\models\command-runner.js:186:24)
    at async default_1 (C:\XXXX\node_modules\@angular\cli\lib\cli\index.js:50:31)

    WebStorm 2019.3 EAP
    Build #WS-193.3519.19, built on September 18, 2019
    WebStorm EAP User
    Expiration date: October 18, 2019
    Runtime version: 11.0.4+10-b480.2 amd64
    VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
    Windows 10 10.0
    GC: ParNew, ConcurrentMarkSweep
    Memory: 1967M
    Cores: 8
    Registry: ide.balloon.shadow.size=0
    Non-Bundled Plugins: AceJump, com.wangbailin.plugin.underscore_case_toggle_to_camel_case, quokka.js, wallaby.js

    • Ekaterina Prigara says:

      Hello Felix,
      Can you please provide a bit more information about the problem? When and where do you see this message? Do you see it if you run your tests in the command line?
      If the problem occurs only in WebStorm and not in the terminal, please contact our tech support and share a sample project that we can use to reproduce the problem. Thank you!

  8. Peter Velkov says:

    Is there a way to run only the changed tests – similar to how jest works in the terminal in “watch” model, where it will only run the affected tests since the last commit

    Once we’ve got more than 200 tests, even though they run quickly we would like to skip running unnecessary tests

    • Ekaterina Prigara says:

      WebStorm integrates with the Jest watch mode – check out the “Run tests in watch mode” section of the blog post. Let me know if you have any questions!

Leave a Reply

Your email address will not be published. Required fields are marked *