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' }
]);
}
}
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();
}
}
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');
});
});
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' }]);
});
});
});