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
Top comments (2)
I just had another terrible experience this week with TestBed and mocking stuff. In the end I'm not even sure anymore for what use cases I would want to use it. The interface is tested through the e2e suite and the rest gets tested with a solid unit test framework like Jest.
(Almost?) no need for TestBed at all.
Really great article. One can generate the codes without the testbed...