Switch to using Jest and Spectator for Angular component testing
Learn how to switch out Karma+Jasmine for Jest with a sprinkling of Spectator
Component testing in Angular has always been a bit of mixed bag; you can test just the typescript but you always have access to the rendered HTML. Switching to Spectator can help you find your groove easier, and backing this up with Jest can improve your dev inner loop, allowing you to developer higher quality Angular components.
To upgrade from Karma+Jasmine to Jest, use the following schematic:
ng add @briebug/jest-schematic
This will give you the option to remove the current karma config, which you should keep only if you know that some of your tests won’t work with Jest.
Once this is done, you’ll have several new files in your project. Because Jest was designed to run JavaScript code, and to run as program and not as a web server, there are certain things that need to be set up so that your code is compiled down to JavaScript before it is run, and also to provide as much mimickery of a real browser as is possible. This last part is achieved by using something called JSDom.
Once you have Jasmine set up, the next thing to do is to add Spectator to your project:
npm install @ngneat/spectator -D
This will save Spectator as a dev dependency, so its code is not included in any builds that are destined for people’s web browsers.
Once you have Spectator set up, creating and managing your components becomes significantly easier.
Learn more about Spectator here: Spectator