Introduction to Unit Testing in Angular

Unit testing has become a must in every software project, it brings benefits such as code quality improvement, documentation of functionality, costs reduction (since bugs can found at early stages) and improves the maintainability of the code.

The purpose of this entry is giving the context of unit testing in the Angular Framework, the kind of tests that could be perform and the tools and benefits the Angular Framework provides out of the box. Said that, unit testing is part of the automation tests as you can see in the image below unit testing is at the bottom of the pyramide which means that usually the costs are lower and the number of tests are bigger.

Now, lets take a look to the types of unit tests that we could create for an Angular application, We can categorize them in three groups.

Type Description
Isolated Tests Tests single unit of code. It is more common to use this kind of tests to test a Service class or a Pipe but you could also test Angular components avoiding the template rendering.
Integration Tests - Shallow tests This a type of integration test used for components where the developer is only interested in testing one component but rendering the template is required to have a test that makes sense. This kind of tests are still isolated but as its name says there is some kind os shallow needed.
Integration Tests - Deep tests This type of tests perform a real integration test and are used to test parent and child Components together.

From my point of view the Angular team has made an excellent work including tools and code generatio for unit tests in the framework, it is really easy to get started with unit testing and probably if you are using the Angular CLI to generate components you already have started. By default the framework uses a javascript testing framework called Jasmine and a test runner called Karma, both solutions are open source projects, lets take a quick look at them.

Jasmine

Jasmine is a javascript testing framework that supports Behaviour Driven Development (A type of Test Driven Development) that makes tests readble and easier to understand for developers and people that is not familiar with code. If you have already created an application using the CLI, your code is ready to be tested. Try this command: ng test

Karma

Karma is a test runner for javascript, basicly it executes the test code using a web server and then displays results in command line and the web browser. This test runner works with Jasmine and other testing frameworks such as Mocha and QUnit.

Now that we have made a litle review about the context of unit testing in the Angular framework and what tools are included by default we are ready to get started with some unit tests.