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

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

  • Add another test for the names$ property

Last updated