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.
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 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.
Signup for my newsletter here.