Angular - testowanie serwisów

Autor podstrony: Krzysztof Zajączkowski

Stronę tą wyświetlono już: 907 razy

Testowanie serwisów jest równie łatwe jak testowanie klas pod warunkiem, że nie wykorzystują one innych serwisów. Serwisy domyślnie są singletonami, to znaczy, że można utworzyć jedną instancję danego serwisu, no chyba że nie skorzysta się z opcji provideIn: root. Oto przykład bardzo prostego serwisu, który wykorzystuje obiekt HttpClient do pobierania z pewnego nieistniejącego api dane:

import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { mergeMap, toArray, switchMap, switchMapTo, map } from 'rxjs/operators'; export interface Client { name: string; surname: string; nip: string; town: string; street: string; house: string; } export class ClientClass implements Client { name: string; surname: string; nip: string; town: string; street: string; house: string; constructor(client: Client) { this.name = client.name; this.surname = client.surname; this.nip = client.nip; this.town = client.town; this.street = client.street; this.house = client.house; } } @Injectable({ providedIn: 'root' }) export class CilentService { constructor( private http: HttpClient ) { } getClientsList(): Observable<ClientClass[]> { return this.http.get<ClientClass[]>( 'https://wwww.example.com.pl/api/clientsList' ) .pipe( mergeMap((obj) => obj), map((obj) => { return new ClientClass(obj); }), toArray() ); } }

Test jednostkowy takiego serwisu może wyglądać np. tak:

import { HttpClient } from '@angular/common/http'; import { TestBed } from '@angular/core/testing'; import { CilentService, Client, ClientClass } from './cilent.service'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { of } from 'rxjs'; class HttpClientMock extends HttpClient { constructor() { super( null ); } } describe('CilentService', () => { let service: CilentService; let http: HttpClient; let clients: Client[]; beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], providers: [ CilentService, { provide: HttpClient, useClass: HttpClientMock } ] }); http = TestBed.inject(HttpClient); service = new CilentService(http); clients = [ { name: 'name1', surname: 'surname1', nip: 'nip1', town: 'town1', street: 'street', house: '1' }, { name: 'name2', surname: 'surname2', nip: 'nip2', town: 'town2', street: 'street2', house: '2' } ]; }); it('should be created', () => { expect(service).toBeTruthy(); }); describe('Should return some data on getClientList', () => { beforeEach( () => { spyOn( http, 'get' ).and.returnValue( of( clients ) ); } ); it( 'Should return data as array of ClientClass', () => { service.getClientsList().subscribe( (values) => { expect( values[0] instanceof ClientClass ).toBeTrue(); } ); } ); } ); });