8. Test the Component logic using a mocked up Service

  • Add an Name interface

    src/app/app.models.ts
    export interface Name {
      name: string;
    }
  • Add a simple service.

ng g service app
src/app/app.service.spec.ts
import { Injectable } from '@angular/core';
import { of, Observable } from 'rxjs';

import { Name } from './app.models';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  constructor() {}

  getCompanies(): Observable<Name[]> {
    return of([
      { name: 'Duncan' },
      { name: 'Sarah' }
    ]);
  }
}
  • Add injected service and new method to getNames() to the AppComponet

src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import { AppService } from './app.service';
import { Name } from './app.models';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'testing';
  names$: Observable<Name[]>;

  constructor(private appService: AppService) {}

  ngOnInit(): void {
    this.getNames();
  }

  getNames() {
    this.names$ = this.appService.getCompanies();
  }

}
  • Add a 'BeforeEach' section before the tests. This will run before each test ('it' sections).

src/app/app.component.spec.ts
import { AppComponent } from './app.component';
import { of } from 'rxjs';
import { AppService } from './app.service';

describe(`Component: App Component`, () => {
  let appService: AppService;
  let component: AppComponent;

  beforeEach(() => {
    fakeAppService = { getNames: () => of([{ name: 'FAKE_NAME' }]) };
    component = new AppComponent(appService);
  });

  it('add 1+1 - PASS', () => {
    expect(1 + 1).toEqual(2);
  });

  it(`title equals 'testing'`, () => {
    expect(component.title).toEqual('testing');
  });
});
  • Add another test for the names$ property

src/app/app.component.spec.ts
import { of } from 'rxjs';

import { AppComponent } from './app.component';
import { AppService } from './app.service';
import { Name } from './app.models';

describe(`Component: App Component`, () => {
  let appService: AppService;
  let component: AppComponent;

  beforeEach(() => {
    appService = { getNames: () => of([{ name: 'FAKE_NAME' }]) };
    component = new AppComponent(appService);
  });

  it('add 1+1 - PASS', () => {
    expect(1 + 1).toEqual(2);
  });

  it(`title equals 'testing'`, () => {
    expect(component.title).toEqual('testing');
  });

  it(`companyCount = 1`, () => {
    component.ngOnInit();
    component.names$.subscribe((names: Name[]) => {
      expect(names).toEqual([{ name: 'FAKE_NAME' }]);
    });
  });
});

Last updated