对具有依赖的Angular服务进行单元测试的几种方式

时间:2022-07-25
本文章向大家介绍对具有依赖的Angular服务进行单元测试的几种方式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

两个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创建代理服务

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 ValueService
        const 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);
      });
});

最后的测试结果: