Get the "Migrating an Angular 1 App to Angular 2 book" for Free. Spread the word and download it now!

When I started developing and writing tests for Angularjs applications, everything felt natural. The tools were mature and I easily got used to developing applications in TDD (Test-Driven Development). It gave me a high level of confidence, knowing that my application was working as I had imagined. Just after Angular 2 came out and I learned the basics, I knew that the next step was to testing.

This article is the first part of a series in which I share my experiences testing different building blocks of an Angular application. We will start with simple use cases and then head for more complex ones.

You may wonder why it is so important to write tests.

Angular Testing Driven Development

With tests, we can ensure the correctness of our application: that the code does what it was designed to do. We can guard against someone breaking our code by refactoring or adding new features. This might have happened to you when someone added a small feature or equivalent code transformations and nothing worked afterwards. Writing tests can clarify the intention of the code by giving usage examples. It can also reveal design flaws. When a piece of code is hard to test, there might be a problem with the underlying architecture.

If you are new to Test-Driven Development, I would recommend reading the Test-Driven Development book by Kent Beck. It gives a nice overview about the concepts and best practices.

Choosing the framework to test Angular

Angular Testing Framework

The first thing we have to choose is the framework. The one suggested by Angular's core team is Jasmine. For a long time it was the only supported testing framework, because test setups were hard wired into the framework. Thanks to refactoring, now tests can also be written in Mocha, or any other framework that supports the beforeEach hook. This hook runs before every test run. If your framework of choice doesn't support it, you have to add the following code snippet to your setup:

import { resetFakeAsyncZone, TestBed } from '@angular/core/testing';

beforeEveryTestHook(() => {
  TestBed.resetTestingModule();
  resetFakeAsyncZone();
});

The first line within the hook resets the internal state of the Dependency Injection container. It clears out any given provider or module. If you are not familiar with Dependency Injection, I would recommend reading the official documentation about it.

The second one clears out any remaining zone that fakes asynchronous operations like setTimeout. Detailed articles can be found on the Thoughtram blog about zones: Understanding zones and Zones in Angular.

For this series, we will be using Jasmine as the test framework.

Writing the first Angular test

Let's look at our first service that will be tested.

import { Injectable } from '@angular/core';

@Injectable()
export class Engine {
  getHorsepower() {
    return 150;
  }

  getName() {
    return 'Basic engine';
  }
}

It has two getter methods and the Injectable decorator. The tests will check whether these getter methods work as intended. The decorator is needed to utilize dependency injection.

In Jasmine, we can group our tests with the describe method. Within this method, we can create test cases with the it function. It is advised to place one class per file (the service) and group the tests around it (with describe). We can further group test cases around methods of the class by placing describe statements inside the top describe block. For now we will only group our tests around the class.

import { Engine } from './engine.service';

describe('Engine', () => {
  it('should return it\'s horsepower', () => {
    let subject = new Engine();

    expect(subject.getHorsepower()).toEqual(150);
  });
});

In this setup, only plain instantiation is used; we will introduce dependency injection later. For basic services, plain instantiation can be enough.

We call the getHorsepower method of the engine and check that it's equal to the expected value.

The first test is green and has been passed. Let's write another one for the getName method.

it('should return it\'s horsepower', () => {
  let subject = new Engine();

  expect(subject.getName()).toEqual('Basic engine');
});

If you run the tests, a similar output will be on the terminal.

Angular First Tests

Both tests have been passed; it is time to refactor. There is duplication at the start of each Angular test. Instantiation is exactly the same, we can move it out into a setup block.

describe('Engine', () => {
  let subject: Engine;

  beforeEach(() => {
    subject = new Engine();
  });

  it('should return it\'s horsepower', () => {
    expect(subject.getHorsepower()).toEqual(150);
  });

  it('should return it\'s horsepower', () => {
    expect(subject.getName()).toEqual('Basic engine');
  });
});

The subject variable is declared at the start of the describe block, and the creation of the service is moved to the beforeEach block. This way we don't have to do it manually every time. It is common to move the creation of the test case subject to a separate method, because it offloads the tests and makes them more readable.

Using Dependency Injection

Creating services directly can be good if the subject under test has no or few, dependencies. But if it has multiple dependencies, or a deeper dependency tree, setting up all the classes becomes tedious. For these situations, we can use Angular's dependency injection management.

The Car class uses the Engine class in the constructor and its instance in the getName method.

import { Injectable } from '@angular/core';
import { Engine } from './engine.service';

@Injectable()
export class Car {
  constructor(private engine: Engine) {}

  getName() {
    return `Car with ${this.engine.getName()}(${this.engine.getHorsepower()} HP)`;
  }
}

We check for the getName method's output in the test after we set up the dependency injection container.

import { TestBed, inject } from '@angular/core/testing';
import { Engine } from './engine.service';
import { Car } from './car.service';

describe('Car', () => {
  let subject: Car;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [Engine, Car]
    });
  });

  beforeEach(inject([Car], (car: Car) => {
    subject = car;
  }));

  it('should display name with engine', () => {
    expect(subject.getName()).toEqual('Car with Basic engine(150 HP)');
  });
});

The difference here is that we configure the TestBed with the provided services in the configureTestingModule method. Only these classes can be instantiated with the inject method. If we try to request something else, we get an error saying it is an unknown provider.

Angular Testing Error

We can request instances of the services in an array from the inject method. In the callback, we get the instances in the same order as in the dependency array with the first parameter. The type hint inside the callback is only for IDE completion; it also works without it. In the example, it is placed inside the beforeEach function, but it can also be added to the it block.

it('should display name with engine', inject([Car], (car: Car) => {
  expect(car.getName()).toEqual('Car with Basic engine(150 HP)');
}));

Mocking

In unit tests for Angular, we want to execute the code in isolation. This means it is not dependent on big, complex objects and is not calling methods that rely on external systems (like HTTP calls or database access). In these cases, we want to simulate the original behavior while skipping the underlying implementation.

When achieved, it is called mocking. We don't have to do it manually. Jasmine provides tools to make it work. Let's assume that the method of the Engine class has a call through to the server and we want to mock it.

...
beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [Engine, Car]
  });

  spyOn(Engine.prototype, 'getHorsepower').and.returnValue(400);
  spyOn(Engine.prototype, 'getName').and.returnValue('V8 engine');
});

...

it('should display name with engine', () => {
  expect(subject.getName()).toEqual('Car with V8 engine(400 HP)');
});

We mock the class methods by calling the spyOn method on the class's prototype. We also alter the return value of the function. This way the original method never gets called. When mocking the prototype, it affects every instance of the class.

Using Dependency Injection for Mocking

The previous solution for mocking can be achieved also with Angular's dependency injection mechanism. We pass the Engine class as the provider token, but create the instances with a fake class.

@Injectable()
class V8Engine {
  getHorsepower() {
    return 400;
  }

  getName() {
    return 'V8 engine';
  }
}

Then we pass this fake class to the setup.

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [
      { provide: Engine, useClass: V8Engine },
      Car
    ]
  });
});

With this setup, the inject call will return an instance of V8Engine when asked for Engine. We can also use useFactory with a callback, or useValue with an instance, to accomplish the same result. The only drawback here is that every method of the class must be implemented and changed whenever the original class changes. The original class can be extended optionally in order to override only specific methods.

Aside: Authenticate an Angular App and Node API with Auth0

We can protect our applications and APIs so that only authenticated users can access them. Let's explore how to do this with an Angular application and a Node API using Auth0. You can clone this sample app and API from the angular-auth0-aside repo on GitHub.

Auth0 centralized login screen

Features

The sample Angular application and API has the following features:

  • Angular application generated with Angular CLI and served at http://localhost:4200
  • Authentication with auth0.js using a centralized Lock instance
  • Node server protected API route http://localhost:3001/api/dragons returns JSON data for authenticated GET requests
  • Angular app fetches data from API once user is authenticated with Auth0
  • Profile page requires authentication for access using route guards
  • Authentication service uses a subject to propagate authentication status events to the entire app
  • User profile is fetched on authentication and stored in authentication service
  • Access token, ID token, profile, and token expiration are stored in local storage and removed upon logout

Sign Up for Auth0

You'll need an Auth0 account to manage authentication. You can sign up for a free account here. Next, set up an Auth0 client app and API so Auth0 can interface with an Angular app and Node API.

Set Up a Client App

  1. Go to your Auth0 Dashboard and click the "create a new client" button.
  2. Name your new app and select "Single Page Web Applications".
  3. In the Settings for your new Auth0 client app, add http://localhost:4200/callback to the Allowed Callback URLs.
  4. Scroll down to the bottom of the Settings section and click "Show Advanced Settings". Choose the OAuth tab and verify that the JsonWebToken Signature Algorithm is set to RS256.
  5. If you'd like, you can set up some social connections. You can then enable them for your app in the Client options under the Connections tab. The example shown in the screenshot above utilizes username/password database, Facebook, Google, and Twitter. For production, make sure you set up your own social keys and do not leave social connections set to use Auth0 dev keys.

Set Up an API

  1. Go to APIs in your Auth0 dashboard and click on the "Create API" button. Enter a name for the API. Set the Identifier to your API endpoint URL. In this example, this is http://localhost:3001/api/. The Signing Algorithm should be RS256.
  2. You can consult the Node.js example under the Quick Start tab in your new API's settings. We'll implement our Node API in this fashion, using Express, express-jwt, and jwks-rsa.

We're now ready to implement Auth0 authentication on both our Angular client and Node backend API.

Dependencies and Setup

The Angular app utilizes the Angular CLI. Make sure you have the CLI installed globally:

$ npm install -g @angular/cli

Once you've cloned the project, install the Node dependencies for both the Angular app and the Node server by running the following commands in the root of your project folder:

$ npm install
$ cd server
$ npm install

The Node API is located in the /server folder at the root of our sample application.

Find the config.js.example file and remove the .example extension from the filename. Then open the file:

// server/config.js
// (formerly config.js.example)
module.exports = {
  CLIENT_DOMAIN: '[CLIENT_DOMAIN]', // e.g. 'you.auth0.com'
  AUTH0_AUDIENCE: 'http://localhost:3001/api/'
};

Change the CLIENT_DOMAIN variable to your Auth0 client domain and set the AUTH0_AUDIENCE to your audience (in this example, this is http://localhost:3001/api/). The /api/dragons route will be protected with express-jwt and jwks-rsa.

Note: To learn more about RS256 and JSON Web Key Set, read Navigating RS256 and JWKS.

Our API is now protected, so let's make sure that our Angular application can also interface with Auth0. To do this, we'll activate the src/app/auth/auth0-variables.ts.example file by deleting .example from the file extension. Then open the file and change the [CLIENT_ID] and [CLIENT_DOMAIN] strings to your Auth0 information:

// src/app/auth/auth0-variables.ts
// (formerly auth0-variables.ts.example)
...
export const AUTH_CONFIG: AuthConfig = {
  CLIENT_ID: '[CLIENT_ID]',
  CLIENT_DOMAIN: '[CLIENT_DOMAIN]',
  ...

Our app and API are now set up. They can be served by running ng serve from the root folder and node server.js from the /server folder.

With the Node API and Angular app running, let's take a look at how authentication is implemented.

Authentication Service

Authentication logic on the front end is handled with an AuthService authentication service: src/app/auth/auth.service.ts file.

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import * as auth0 from 'auth0-js';
import { AUTH_CONFIG } from './auth0-variables';
import { UserProfile } from './profile.model';

@Injectable()
export class AuthService {
  // Create Auth0 web auth instance
  // @TODO: Update AUTH_CONFIG and remove .example extension in src/app/auth/auth0-variables.ts.example
  auth0 = new auth0.WebAuth({
    clientID: AUTH_CONFIG.CLIENT_ID,
    domain: AUTH_CONFIG.CLIENT_DOMAIN,
    responseType: 'token id_token',
    redirectUri: AUTH_CONFIG.REDIRECT,
    audience: AUTH_CONFIG.AUDIENCE,
    scope: AUTH_CONFIG.SCOPE
  });
  userProfile: UserProfile;

  // Create a stream of logged in status to communicate throughout app
  loggedIn: boolean;
  loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);

  constructor() {
    // If authenticated, set local profile property and update login status subject
    if (this.authenticated) {
      this.userProfile = JSON.parse(localStorage.getItem('profile'));
      this.setLoggedIn(true);
    }
  }

  setLoggedIn(value: boolean) {
    // Update login status subject
    this.loggedIn$.next(value);
    this.loggedIn = value;
  }

  login() {
    // Auth0 authorize request
    this.auth0.authorize();
  }

  handleAuth() {
    // When Auth0 hash parsed, get profile
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        window.location.hash = '';
        this._getProfile(authResult);
      } else if (err) {
        console.error(`Error: ${err.error}`);
      }
    });
  }

  private _getProfile(authResult) {
    // Use access token to retrieve user's profile and set session
    this.auth0.client.userInfo(authResult.accessToken, (err, profile) => {
      this._setSession(authResult, profile);
    });
  }

  private _setSession(authResult, profile) {
    const expTime = authResult.expiresIn * 1000 + Date.now();
    // Save session data and update login status subject
    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('profile', JSON.stringify(profile));
    localStorage.setItem('expires_at', JSON.stringify(expTime));
    this.userProfile = profile;
    this.setLoggedIn(true);
  }

  logout() {
    // Remove tokens and profile and update login status subject
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    localStorage.removeItem('expires_at');
    this.userProfile = undefined;
    this.setLoggedIn(false);
  }

  get authenticated(): boolean {
    // Check if current date is greater than expiration
    const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return Date.now() < expiresAt;
  }

}

This service uses the config variables from auth0-variables.ts to instantiate an auth0.js WebAuth instance.

An RxJS BehaviorSubject is used to provide a stream of authentication status events that you can subscribe to anywhere in the app.

The login() method authorizes the authentication request with Auth0 using your config variables. An Auth0 centralized login page will be shown to the user and they can then log in.

Note: If it's the user's first visit to our app and our callback is on localhost, they'll also be presented with a consent screen where they can grant access to our API. A first party client on a non-localhost domain would be highly trusted, so the consent dialog would not be presented in this case. You can modify this by editing your Auth0 Dashboard API Settings. Look for the "Allow Skipping User Consent" toggle.

We'll receive idToken, accessToken, and expiresIn in the hash from Auth0 when returning to our app. The handleAuth() method uses Auth0's parseHash() method callback to get the user's profile (_getProfile()) and set the session (_setSession()) by saving the tokens, profile, and token expiration to local storage and updating the loggedIn$ subject so that any subscribed components in the app are informed that the user is now authenticated.

Note: The profile takes the shape of profile.model.ts from the OpenID standard claims.

The handleAuth() method can then be called in the app.component.ts constructor like so:

// src/app/app.component.ts
import { AuthService } from './auth/auth.service';
...
  constructor(private auth: AuthService) {
    // Check for authentication and handle if hash present
    auth.handleAuth();
  }
...

Finally, we have a logout() method that clears data from local storage and updates the loggedIn$ subject. We also have an authenticated accessor to return current authentication status based on access token expiration.

Once AuthService is provided in app.module.ts, its methods and properties can be used anywhere in our app, such as the home component.

Callback Component

The callback component is where the app is redirected after authentication. This component simply shows a loading message until the login process is completed. It subscribes to the loggedIn$ Behavior Subject from our Authentication service in order to redirect back to the home page once the user is logged in, like so:

// src/app/callback/callback.component.ts
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { AuthService } from './../auth/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-callback',
  templateUrl: './callback.component.html',
  styleUrls: ['./callback.component.css']
})
export class CallbackComponent implements OnInit {

  constructor(private auth: AuthService, private router: Router) { }

  ngOnInit() {
    this.auth.loggedIn$.subscribe(
      loggedIn => loggedIn ? this.router.navigate(['/']) : null
    )
  }

}

Making Authenticated API Requests

In order to make authenticated HTTP requests, we need to add a Authorization header with the access token in our api.service.ts file.

// src/app/api.service.ts
...
  getDragons$(): Observable<any[]> {
    return this.http
      .get(`${this.baseUrl}dragons`, {
        headers: new HttpHeaders().set(
          'Authorization', `Bearer ${localStorage.getItem('access_token')}`
        )
      })
      .catch(this._handleError);
  }
...

Final Touches: Route Guard and Profile Page

A profile page component can show an authenticated user's profile information. However, we only want this component to be accessible if the user is logged in.

With an authenticated API request and login/logout implemented, the final touch is to protect our profile route from unauthorized access. The auth.guard.ts route guard can check authentication and activate routes conditionally. The guard is implemented on specific routes of our choosing in the app-routing.module.ts file like so:

// src/app/app-routing.module.ts
...
import { AuthGuard } from './auth/auth.guard';
...
      {
        path: 'profile',
        component: ProfileComponent,
        canActivate: [
          AuthGuard
        ]
      },
...

More Resources

That's it! We have an authenticated Node API and Angular application with login, logout, profile information, and protected routes. To learn more, check out the following resources:

Conclusion: What we've learned about Angular Testing

In this tutorial, we managed to:

  • create a basic service and write tests for it
  • use dependency injection in tests
  • fake dependencies with Jasmine
  • fake dependencies with dependency injection

If you follow the steps introduced in this article and write tests for your Angular application, you can sleep safe and sound. The code will work as intended and when someone accidentally breaks it, the tests will warn him that those changes are unsafe and shouldn't be committed until the tests are green again.

Jasmine will help you along the way with its easy syntax and batteries included (assertion and mocking library).

I hope this has convinced you that writing tests in Angular is not an overly complicated thing.

To make the start even easier, the code is available in this GitHub repository.