对具有外部依赖的Angular服务类(service class)进行单元测试的几种方式
生活随笔
收集整理的這篇文章主要介紹了
对具有外部依赖的Angular服务类(service class)进行单元测试的几种方式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
兩個service的源代碼:
import { Injectable } from '@angular/core';@Injectable() export class MasterService {constructor(private valueService: ValueService) { }getValue() { return this.valueService.getValue(); } }export class ValueService {getValue() { return 'Jerry'; } }單元測試方法1 - 直接實例化真實的被依賴ValueService
import { MasterService, ValueService } from './master.service';describe('MasterService without Angular testing support', () => {let masterService: MasterService;it('#getValue should return real value from the real service', () => {masterService = new MasterService(new ValueService());expect(masterService.getValue()).toBe('Jerry');}); // end of it function });方法2 - 使用fake object替代被依賴的ValueService
it('#getValue should return faked value from a fake object', () => {const fake = { getValue: () => 'fake value' };masterService = new MasterService(fake as ValueService);expect(masterService.getValue()).toBe('fake value');});方法3 - 使用jasmine.createSpyObj創(chuàng)建代理服務
describe('MasterService with Angular testing support', () => {let masterService: MasterService;it('#getValue should return stubbed value from a spy', () => {// create `getValue` spy on an object representing the ValueServiceconst valueServiceSpy =jasmine.createSpyObj('ValueService', ['getValue']);// set the value to return when the `getValue` spy is called.const stubValue = 'stub value';valueServiceSpy.getValue.and.returnValue(stubValue);masterService = new MasterService(valueServiceSpy);expect(masterService.getValue()).toBe(stubValue, 'service returned stub value');expect(valueServiceSpy.getValue.calls.count()).toBe(1, 'spy method was called once');expect(valueServiceSpy.getValue.calls.mostRecent().returnValue).toBe(stubValue);}); });最后的測試結果:
總結
以上是生活随笔為你收集整理的对具有外部依赖的Angular服务类(service class)进行单元测试的几种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 歼-20出击!《长空之王》今日内地上映:
- 下一篇: 下载量超 3500 万次,谷歌 Play