The Angular CLI is Creating Your Unit Tests Wrong

Joe Eames
Thinkster.io
Published in
3 min readSep 17, 2020

I love the Angular CLI. It’s effective, it’s powerful, it’s convenient, and it’s easy to learn. But there’s one thing I really dislike about it, and that’s the way it generates tests.

First some background.

Angular has a testing utility called the TestBed. This utility allows you to run Angular in a limited testing mode so that you can run just a few pieces of an entire angular application during a unit test. This way you can test a component with its template. A very useful capability…WHEN it’s needed. But the TestBed has some drawbacks.

First, it’s heavy. It adds overhead to the execution of your tests. There’s a lot of scaffolding that has to run when the TestBed is executing. Second, it adds a bunch of ceremony to your unit tests. It can easily take 10 to 20 lines of code to configure the TestBed.

Sure, it’s nice to test the pieces of your Angular app as if they were running inside the Angular runtime, but the reality is that most of the time you don’t need this. Angular components, services, directives, pipes, etc. are all just JavaScript classes. If you ignore the Angular-specific decorators, then you’re just dealing with plain old JavaScript.

Let’s take a look at an example Angular component

And now let’s look at the test that the Angular CLI Generates for this class: (don’t bother trying to understand all the code, just glance at it)

That’s about 20 lines of code.

Now let’s look at the component again, but we’ll ignore the component decorator.

That’s just a javaScript class. We can write unit tests for JavaScript classes without some heavy test-time engine like Angular’s TestBed.

That’s only 11 lines of code. And although we can’t test anything in the template now, we can still test the code in the component itself. In most cases, this is where the stuff lives that really needs to be unit tested.

So next time you’re using the CLI to generate your tests, take a minute and reconsider. You may be better off to write more simple, plain tests without the TestBed.

Happy coding!

Signup for my newsletter here.

Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @GoThinkster

--

--

Joe Eames
Thinkster.io

Mormon, Christian, Father, CEO of Thinkster.io, Organizer of @ngconf, @frameworksummit, React Conf. Front end developer, and Software Craftsmanship Evangelist.