Get all your news in one place.
100’s of premium titles.
One app.
Start reading
Forbes
Forbes
Technology
Zach Shuffield, Forbes Staff

How To Make Your Angular Unit Tests 2.5x Faster

It’s tedious to write unit tests. They aren’t fun, and they don’t add any shiny new features. To make it easier, Angular provides us with tools to test “all the things”. But these tools have their limits. And with them come some pretty nasty memory leaks.

Angular testing with the ‘TestBed’, Angular’s built in unit testing API, isn’t purely unit testing. Testing in Angular is more like writing integration tests.

Not only does the TestBed render the component for testing purposes, but it also renders and re-renders the component’s template every test as well. Angular 9 has done a great job at improving this, but even the Angular team is moving towards testing services as classes in their testing services documentation. I’m going to show you a way to ditch the TestBed, and write purely class based unit tests. Not only will they be cleaner, but also a fair degree faster.

Testing as a class: The How

Instead of using the TestBed to inject services into your test component, you can use the ‘new’ keyword to create an object instance of your component. You then can pass in the required services into the constructor as parameters.

The finished product will look something like this:

This will make your unit tests truly unit tests. You will also see it helps with performance. It eliminates rendering a component and running angular change detection on every test. I’ve seen speed improvements as much as 2 and a half times.

Don’t want to leave the test bed behind? Angular 9 has some pretty nice improvements, and not just in regards to unit testing (Ivy renderer 🙌). Along with the Angular upgrade, keeping a lot of your business logic inside services rather than in components themselves will also help testing performance.

Happy testing!

Sign up to read this article
Read news from 100’s of titles, curated specifically for you.
Already a member? Sign in here
Related Stories
Top stories on inkl right now
One subscription that gives you access to news from hundreds of sites
Already a member? Sign in here
Our Picks
Fourteen days free
Download the app
One app. One membership.
100+ trusted global sources.