Angular Testing: Using Spies

Jasmine spies are used to track or stub functions or methods. Spies are an easy 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 a 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.

Let’s use an example very similar to what we used in our introduction to unit tests in Angular. Our simple app allows to increment a value between 0 and 15. This time though, the logic is handled by a service, which will allow multiple components to access the same central value. Here’s our service:

increment-decrement.service.ts

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

@Injectable()
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!';
    }
  }
}

Our component and template look like this:

app.component.ts

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

@Component({
  selector: 'app-root',
  template:
  `<h1>{{ incrementDecrement.value }}</h1>

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

  <p class="message">
    {{ incrementDecrement.message }}
  </p>`
})
export class AppComponent {
  constructor(public incrementDecrement: IncrementDecrementService) {}

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

With this in place, we can define our component’s unit tests like this:

app.component.spec.ts

import { TestBed, async, 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(async(() => {
    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 see how to use spies to check if methods have been called or to provide a stub return value.

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:

app.component.spec.ts

// Same imports as previously

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

  beforeEach(async(() => {
    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.

Let’s say we want to assert that the method was called twice:

expect(incrementSpy).toHaveBeenCalledTimes(2);

Or that it wasn’t called with the argument 'foo':

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

Providing a Return Value

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:

minimumOrMaximumReached() {
  return !!(this.message && this.message.length); // will return true or false
}

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:

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

Now our template show a message if the limit is reached with this:

<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:

app.component.spec.ts

// Same imports as previously

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

  beforeEach(async(() => {
    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!');
  });
});
✖ Clear

🕵 Search Results

🔎 Searching...