Testing Angular faster with Jest

It struck me how painful experience it was to test an Angular app. And then I realized it can be painless with Jest.

Note: This article assumes you are using an Angular CLI v1.0 generated project from Angular v4.0.0. But it too works on Angular v2.x with CLI in beta.

Despite Angular being a comprehensive framework with lots of default abstractions: e.g. custom JIT and AOT compilers, deep RxJS and Zone.js integration, it’s still possible to work outside of its toolbox. Interestingly, it’s possible to change the default test runner. This post will tell you why, and how you can do it.

And what’s most important is that it provides a smart, immersive watch mode. The watch mode runs only tests affected by git file changes – it also runs failed tests first and is able to bail on first error so the feedback loop is ~10x faster than with Karma, depending on test suite size.

To the point – I want my Angular tests faster now!

We need to install necessary dependencies (I’m using yarn, but if you fancy npm, no problems):

$ yarn add --dev jest jest-preset-angular @types/jest

where:

jest – Jest testing platform

jest-preset-angular – configuration preset with common settings setup for you

This is mostlikely all configuration you'll need. I've extracted common configuration options into jest-preset-angular package and it should just work™ for most cases.

Note: setups differ and you may need to tailor the config specifically to your app needs. You should then findREADME of the preset helpful. It's also worth noting that every option set by preset may be simply overwritten.

Next step – create setupJest.ts. This little guy you can write in TS, also making sure to place it into /src as well. It looks like this:

import 'jest-preset-angular';
import './jestGlobalMocks';

You can see that we’re importing jestGlobalMocks.ts file with patches to our window object (jsdom doesn’t have it all implemented so we need to patch it sometimes).

Mocking localStorage is optional, but without mocking getComputedStyle your test won’t run, as Angular checks in which browser it executes. We need to fake it.

You’re now ready to add this to your npm scripts:

"test": "jest",
"test:watch": "jest --watch",

...and change the way you test Angular apps forever.

Oh, one more thing. Forget about installing PhantomJS on your CI:

"test:ci": "jest --runInBand",

It's worth noting that CI servers usually run your code on single core, so parallelization may slow your tests down. If you're experiencing such behavior, use --runInBand flag to tell Jest explicitly that you want to run tests one-by-one (just like Karma or Mocha).

Caveats

Of course, there are some. But surprisingly not many.

Migration from Jasmine

We’ll need to migrate some of Jasmine calls to Jest. Most of the API is similar but there are slight differences.

Farewell browser, our tests now run in jsdom

You can also bump into APIs available in browsers but not in jsdom, like htmlElement.closest or window.localStorage (which we just mocked in jestGlobalMocks.ts).

Zone.js messy error stack trace

I couldn't force Zone to output shorter and more meaningful error stack traces. As a workaround you can add Error.stackTraceLimit = 2; to your setupJest.ts or whatever number suites you. I find it useful for most cases.

IDE integrations

Be sure to also check these awesome extensions to ease testing experience even more:

Summary

I was truly amazed that it’s actually possible to integrate a 3rd party testing tool not running in browser, like Jest, into Angular. Couple of days ago I still thought that it will be impossible to do so within reasonable amount of time and it’s just not worth the effort, but turned out it was so worth it.

Our app's whole test suite of 35 files with ~100 tests executed 2.5x faster than with Karma. We can also use snapshot testing. What’s most important though, we now have powerful watch mode, rerunning tests instantly. And all of this without the need of compiling the app or running a dev server.

So if you care about your testing experience, do yourself a favor and run Angular tests with Jest. You’ll love it.

Comments

Jest looks like a big improvement over Karma. But actually something exists that is even better into terms of feedback speed and quality: wallabyjs. Try it out!

kpax•
April 3, 2017

I can't seem to figure out how to get webpack to run through it's loaders first, like angular2-template-loader to do what your preprocessor is doing. Is there a way to get jest to kick off a webpack bundle first?

Michal Pierzchala•
April 4, 2017

kpax Running your code through Jest and Webpack are two different things. One doesn’t know about the other. Here you’ll find a Webpack tutorial on official Jest docs. You’ll probably need to adjust moduleNameMapper to suite your needs. You can also submit an issue on jest-preset-angular and we’ll see what can be done. Good luck!

Dominic Watson•
April 4, 2017

Feel like I'm being dumb and missing something, but is this for ejected CLIs?
Using on a project out of the box I get: `SyntaxError: Unexpected token import` as it runs through each of the tests.

Brady Isom•
April 4, 2017

I was excited about trying to add Jest to my Angular 4.x/AngularCli project. Thank you for the post. However, In following the instructions, I am seeing an error when Jest tries to load the setupJest.ts file:

at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
at handle (node_modules/worker-farm/lib/child/index.js:41:8)
at process. (node_modules/worker-farm/lib/child/index.js:47:3)
at emitTwo (events.js:106:13)

Hello there,
very nice article. i manage to execute 208 tests in around 30 secs in the best case. which is quite good, but i want it even faster. the problem seems to be in some initial step, as only the first tests take long (6 - 10 secs -> each worker ) and the following up are really quick.

do you have any idea to investigate what takes so long initially? i am using uptodate versions of ng (4.0.1) and ng-cli (1.0.0)

Cheers Andi

Michal Pierzchala•
April 18, 2017

Hey danAnderl!
The following runs are faster, because the cache is "warm". On the first run Jest scans all necessary files and transform them from TypeScript to JS. Transforming takes some time, so the results (JS files) are cached – this way the files are only transformed through tsc (or any other transformer, e.g. babel) only once, and after they're changed.
Glad it works for you!

Jan•
April 20, 2017

Thanks for the great article and project ... I still have a question concerning Snapshot testing ... is there an equivalent to the react-renderer i can use in Angular projects?

Thank you so much for the post. Your approach and the Jest framework look very interesting. I have my own Angular* skeleton project that I've been working on. I tried to integrate your approach, but am running into some issues. Namely, I keep getting an error trying to run the tests relating to zone-node.js. If you would be willing to look, the repository is on GitHub: https://github.com/PdUi/angular-aspnet-skeletons/tree/jest-integration/ng-custom
I assume you ran into a similar issue and would greatly appreciate any help you could offer.

Thanks again for the very informative post!!!

Michal Pierzchala•
May 10, 2017

Eniep Yrekcaz, checkout the PR I sent you :)

Eniep Yrekcaz•
May 10, 2017

You are awesome. I really appreciate it!!!

Andrew Krueger•
May 17, 2017

Michal Pierzchala, what's the benefit of using Jest with Webpack rather than running it normally?

Michal Pierzchala•
May 18, 2017

Andrew Krueger, I'm sorry, but I don't know what are you referring to. Please be more specific.

Jon Caris, that doesn't tell much. But if you can provide a repository with the reproduction of the problem, please post it on Jest issue tracker

David Atencia•
May 27, 2017

Awesome! I have been able to integrate Jest into an Ionic2 project with a little change following the instructions in this article. Really easy to set-up.

Many thanks for the article

YuJM•
June 15, 2017

i using material2
i could not test ( dependency material2 components files )
how do i do?

Carl•
July 22, 2017

This article is awesome and the angular jest preset is great. I'm having one little issue that I hope you can help with. When I change one file, jest runs all of my tests rather than the tests relating to the file that changed, do you know why this is?

Thomas•
August 10, 2017

Nice article. Any suggestion why the paths in the tsconfig seem not to be resolved?
My tests are crashing when using absolute imports based on the paths defined there.