Skip to main content
  1. Tutorials/

How To Use Spies in Angular Testing

Tutorials Angular
Introduction>

Introduction #

Jasmine spies are used to track or stub functions or methods. Spies are a way to check if a function was called or to provide a custom return value. We can use spies to test components that depend on service and avoid actually calling the service’s methods to get a value. This helps keep our unit tests focused on testing the internals of the component itself instead of its dependencies.
In this article, you will learn how to use Jasmine spies in an Angular project.

Prerequisites>

Prerequisites #

To complete this tutorial, you will need:

Node.js installed locally, which you can do by following How to Install Node.js and Create a Local Development Environment.
Some familiarity with setting up an Angular project.

This tutorial was verified with Node v16.2.0, npm v7.15.1, and @angular/core v12.0.4.

Step 1 — Setting Up the Project>

Step 1 — Setting Up the Project #

Let’s use an example very similar to what we used in our introduction to unit tests in Angular.
First, use @angular/cli to create a new project:

ng new angular-test-spies-example

Then, navigate to the newly created project directory:

cd angular-test-spies-example

Previously, the application used two buttons to increment and decrement values between 0 and 15.
For this tutorial, the logic will be moved to a service. This will allow multiple components to access the same central value.

ng generate service increment-decrement

Then open increment-decrement.service.ts in your code editor and replace the content with the following code:
src/app/increment-decrement.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class IncrementDecrementService {
  value = 0;
  message!: string;

  increment() {
    if (this.value < 15) {
      this.value += 1;
      this.message = '';
    } else {
      this.message = 'Maximum reached!';
    }
  }

  decrement() {
    if (this.value > 0) {
      this.value -= 1;
      this.message = '';
    } else {
      this.message = 'Minimum reached!';
    }
  }
}

Open app.component.ts in your code editor and replace the content with the following code:
src/app/app.component.ts

import { Component } from '@angular/core';
import { IncrementDecrementService } from './increment-decrement.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(public incrementDecrement: IncrementDecrementService) { }

  increment() {
    this.incrementDecrement.increment();
  }

  decrement() {
    this.incrementDecrement.decrement();
  }
}

Open app.component.html in your code editor and replace the content with the following code:
src/app/app.component.html

<h1>{{ incrementDecrement.value }}</h1>

<hr>

<button (click)="increment()" class="increment">Increment</button>

<button (click)="decrement()" class="decrement">Decrement</button>

<p class="message">
  {{ incrementDecrement.message }}
</p>

Next, open app.component.spec.ts in your code editor and modify the following lines of code:
src/app/app.component.spec.ts

import { TestBed, waitForAsync, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { AppComponent } from './app.component';
import { IncrementDecrementService } from './increment-decrement.service';

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let debugElement: DebugElement;
  let incrementDecrementService: IncrementDecrementService;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers: [ IncrementDecrementService ]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    debugElement = fixture.debugElement;

    incrementDecrementService = debugElement.injector.get(IncrementDecrementService);
  }));

  it('should increment in template', () => {
    debugElement
      .query(By.css('button.increment'))
      .triggerEventHandler('click', null);

    fixture.detectChanges();

    const value = debugElement.query(By.css('h1')).nativeElement.innerText;

    expect(value).toEqual('1');
  });

  it('should stop at 15 and show maximum message', () => {
    incrementDecrementService.value = 15;
    debugElement
      .query(By.css('button.increment'))
      .triggerEventHandler('click', null);

    fixture.detectChanges();

    const value = debugElement.query(By.css('h1')).nativeElement.innerText;
    const message = debugElement.query(By.css('p.message')).nativeElement.innerText;

    expect(value).toEqual('15');
    expect(message).toContain('Maximum');
  });
});

Notice how we can get a reference to the injected service with debugElement.injector.get.
Testing our component this way works, but actual calls will also be made to the service, and our component is not tested in isolation. Next, we’ll explore how to use spies to check if methods have been called or to provide a stub return value.

Step 2 — Spying on a Service’s Methods>

Step 2 — Spying on a Service’s Methods #

Here’s how you’d use Jasmine’s spyOn function to call a service method and test that it was called:
src/app/app.component.spec.ts

import { TestBed, waitForAsync, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { AppComponent } from './app.component';
import { IncrementDecrementService } from './increment-decrement.service';

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let debugElement: DebugElement;
  let incrementDecrementService: IncrementDecrementService;
  let incrementSpy: any;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers: [ IncrementDecrementService ]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    debugElement = fixture.debugElement;

    incrementDecrementService = debugElement.injector.get(IncrementDecrementService);
    incrementSpy = spyOn(incrementDecrementService, 'increment').and.callThrough();
  }));

  it('should call increment on the service', () => {
    debugElement
      .query(By.css('button.increment'))
      .triggerEventHandler('click', null);

    expect(incrementDecrementService.value).toBe(1);
    expect(incrementSpy).toHaveBeenCalled();
  });
});

spyOn takes two arguments: the class instance (our service instance in this case) and a string value with the name of the method or function to spy.
Here we also chained .and.callThrough() on the spy, so the actual method will still be called. Our spy in this case is only used to be able to tell if the method was actually called and to spy on the arguments.
Here is an example of asserting that a method was called twice:

expect(incrementSpy).toHaveBeenCalledTimes(2);

Here is an example of asserting that a method was not called with the argument 'error':

expect(incrementSpy).not.toHaveBeenCalledWith('error');

If we want to avoid actually calling the methods on the service we can use .and.returnValue on the spy.
Our example methods are not good candidates for this because they don’t return anything and instead mutate internal properties.
Let’s add a new method to our service that actually returns a value:
src/app/increment-decrement.service.ts

minimumOrMaximumReached() {
  return !!(this.message && this.message.length);
}

Note: Using !! before an expression coerces the value into a boolean.

We also add a new method to our component that will be used by the template to get to the value:
src/app/app.component.ts

limitReached() {
  return this.incrementDecrement.minimumOrMaximumReached();
}

Now our template show a message if the limit is reached with this:
src/app/app.component.html

<p class="message" *ngIf="limitReached()">
  Limit reached!
</p>

We can then test that our template message will show if the limit is reached without having to resort to actually calling the method on the service:
src/app/app.component.spec.ts

import { TestBed, waitForAsync, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { AppComponent } from './app.component';
import { IncrementDecrementService } from './increment-decrement.service';

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let debugElement: DebugElement;
  let incrementDecrementService: IncrementDecrementService;
  let minimumOrMaximumSpy: any;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers: [ IncrementDecrementService ]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    debugElement = fixture.debugElement;

    incrementDecrementService = debugElement.injector.get(IncrementDecrementService);
    minimumOrMaximumSpy = spyOn(incrementDecrementService, 'minimumOrMaximumReached').and.returnValue(true);
  }));

  it(`should show 'Limit reached' message`, () => {
    fixture.detectChanges();

    const message = debugElement.query(By.css('p.message')).nativeElement.innerText;

    expect(message).toEqual('Limit reached!');
  });
});
Conclusion>

Conclusion #

In this article, you learned how to use Jasmine spies in an Angular project.
If you’d like to learn more about Angular, check out our Angular topic page for exercises and programming projects.