With the unit tests, we can make sure that the individual parts of the application work exactly as we expect from them.import { Injectable } from '@angular/core'; import { ReplaySubject } from 'rxjs/ReplaySubject'; @Injectable() export class PopupService { private popupDialog = new ReplaySubject<{popupEvent: string, component?, options?: {}}>(); public popupDialog$ = this.popupDialog.asObservable(); open(component, options?: {}) { this.popupDialog.next({popupEvent: 'open', component: component, options: options}); } close() { this.popupDialog.next({popupEvent: 'close'}); } } import { PopupService } from './popup.service'; import { SignInComponent } from '../components/signin/signin.component'; describe('PopupService', () => { let service: PopupService; // PopupService beforeEach(() => { service = new PopupService(); }); // done , it('subscribe for opening works', (done: DoneFn) => { // open service.open(SignInComponent, [{title: ' ', message: ''}]); // popupDialog$ subscribe service.popupDialog$.subscribe((data) => { expect(data.popupEvent).toBe('open'); done(); }); }); it('subscribe for closing works', (done: DoneFn) => { service.close(); service.popupDialog$.subscribe((data) => { expect(data.popupEvent).toBe('close'); done(); }); }); }); import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; } <h1> Welcome to {{ title }}! </h1> beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; }); it('should create the comp', => { expect(comp).toBeTruthy(); }); it(`should have as title 'app'`, () => { expect(comp.title).toEqual('app'); }); it('should render title in a h1 tag', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent) .toContain('Welcome to app!'); }); import { TestBed, async, ComponentFixture } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { let comp: AppComponent; let fixture: ComponentFixture<AppComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; }); it('should create the comp', () => { expect(comp).toBeTruthy(); }); it(`should have as title 'app'`, () => { expect(comp.title).toEqual('app'); }); it('should render title in a h1 tag', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent) .toContain('Welcome to app!'); }); }); export class AppComponent { constructor(private popup: PopupService) { } title = 'app'; } TestBed.configureTestingModule({ declarations: [ AppComponent ], providers: [PopupService] }); const popupServiceStub = { open: () => {} }; class popupServiceStub { open() {} } providers: [{provide: PopupService, useClass: popupServiceStub } ] providers: [{provide: PopupService, useValue: popupServiceStub } ] ngOnInit() { this.popup.open(SignInComponent); } popup = TestBed.get(PopupService); popup = fixture.debugElement.injector.get(PopupService); it('should called open', () => { const openSpy = jest.spyOn(popup, 'open'); fixture.detectChanges(); expect(openSpy).toHaveBeenCalled(); }); beforeEach(() => TestBed.configureTestingModule({ imports: [HttpModule], providers: [ MockBackend, BaseRequestOptions, { provide: Http, useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions), deps: [MockBackend, BaseRequestOptions] }, UserService ] })); import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import { Game } from '../models/gameModel'; import { StatisticsService } from './statistics.service'; @Injectable() export class GameService { gameData: Array<Game>; dataChange: ReplaySubject<any>; gamesUrl = 'https://any.com/games'; constructor(private http: HttpClient, private statisticsService: StatisticsService) { this.dataChange = new ReplaySubject(); } getGames() { this.makeResponse() .subscribe((games: Array<Game>) => { this.handleGameData(games); }); } makeResponse(): Observable<any> { return this.http.get(this.gamesUrl); } handleGameData(games) { this.gameData = games; this.doNext(games); this.statisticsService.send(); } doNext(value) { this.dataChange.next(value); } } let http: HttpTestingController; let service: GameService; let statisticsService: StatisticsService; const statisticsServiceStub = { send: () => {} }; const expectedData = [ {id: '1', name: 'FirstGame', locale: 'ru', type: '2'}, {id: '2', name: 'SecondGame', locale: 'ru', type: '3'}, {id: '3', name: 'LastGame', locale: 'en', type: '1'}, ]; TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, ], providers: [GameService, { provide: StatisticsService, useValue: statisticsServiceStub }] }); service = TestBed.get(GameService); statisticsService = TestBed.get(StatisticsService); http = TestBed.get(HttpTestingController); afterEach(() => { http.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should have made one request to GET data from expected URL', () => { service.makeResponse().subscribe((data) => { expect(data).toEqual(expectedData); }); const req = http.expectOne(service.gamesUrl); expect(req.request.method).toEqual('GET'); req.flush(expectedData); }); it('getGames should emits gameData', () => { service.getGames(); service.dataChange.subscribe((data) => { expect(data).toEqual(expectedData); }); const req = http.expectOne(service.gamesUrl); req.flush(expectedData); }); it('statistics should be sent', () => { const statisticsSpy = jest.spyOn(statisticsService, 'send'); service.handleGameData(expectedData); expect(statisticsSpy).toHaveBeenCalled(); }); import { TestBed } from '@angular/core/testing'; import { GameService } from './game.service'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { StatisticsService } from './statistics.service'; import 'rxjs/add/observable/of'; describe('GameService', () => { let http: HttpTestingController; let service: GameService; let statisticsService: StatisticsService; const statisticsServiceStub = { send: () => {} }; const expectedData = [ {id: '1', name: 'FirstGame', locale: 'ru', type: '2'}, {id: '2', name: 'SecondGame', locale: 'ru', type: '3'}, {id: '3', name: 'LastGame', locale: 'en', type: '1'}, ]; beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, ], providers: [GameService, { provide: StatisticsService, useValue: statisticsServiceStub }] }); service = TestBed.get(GameService); statisticsService = TestBed.get(StatisticsService); http = TestBed.get(HttpTestingController); }); afterEach(() => { http.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should have made one request to GET data from expected URL', () => { service.makeResponse().subscribe((data) => { expect(data).toEqual(expectedData); }); const req = http.expectOne(service.gamesUrl); expect(req.request.method).toEqual('GET'); req.flush(expectedData); }); it('getGames should emits gameData', () => { service.getGames(); service.dataChange.subscribe((data) => { expect(data).toEqual(expectedData); }); const req = http.expectOne(service.gamesUrl); req.flush(expectedData); }); it('statistics should be sent', () => { const statisticsSpy = jest.spyOn(statisticsService, 'send'); service.handleGameData(expectedData); expect(statisticsSpy).toHaveBeenCalled(); }); }); TestBed.configureTestingModule({ declarations: [ AppComponent ], schemas: [ NO_ERRORS_SCHEMA ] }) Source: https://habr.com/ru/post/349380/
All Articles