Angular Tests Made Easy With Spectator

Netanel Basal
Netanel Basal
Published in
2 min readSep 13, 2017

--

Writing tests for our code is part of our daily routine. When working on large applications with many components, it can take time and effort.

Although Angular provides us with great tools to deal with these things, it still requires quite a lot of boilerplate work.

For this reason, I decided to create a library that will make it easier for us to write tests by cutting the boilerplate and add custom Jasmine matchers.

Spectator helps you get rid of all the boilerplate grunt work, leaving you with readable, sleek and streamlined unit tests.

Let’s look at some examples.

The first step is to install the library through npm or yarn.

npm install @netbasal/spectator --save-dev

Building The Zippy Component

Let’s create a simple zippy component for testing.

Testing The Zippy Component

To test it we will use the createHostComponentFactory() method.

As you can see, this way removes most of the boilerplate and gives you a clear focus on the important things, and it’s also much more readable.

Now, let’s see another way to write tests without a host element.

Building The Button Component

Let’s create a simple button component for testing.

Testing The Button Component

To test it we will use the createTestComponentFactory() method.

This is just a taste of the library’s capabilities. You can find the full documentation here. If you have requests, comments or you want to contribute, I would love to hear.

More useful libraries from the creator: ngx-auto-unsubscribe, ngrx-generator, ngx-take-until-destroy, helpful-decorators.

Follow me on Medium or Twitter to read more about Angular, Vue and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.