本文介绍了使用Jasmine angular2注入的私有服务进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试对角度服务进行单元测试时遇到问题.我想验证此服务是否正确调用了注入其中的另一个服务.

I have a problem trying to unit test an angular service. I want to verify that this service is properly calling another service that is injected into it.

让我们说我有这个ServiceToTest注入ServiceInjected:

Lets say I have this ServiceToTest that injects ServiceInjected:

ServiceToTest .service.ts

ServiceToTest .service.ts

@Injectable()
export class ServiceToTest  {
    constructor(private _si: ServiceInjected) {}
    public init() {
      this._si.configure();
    }

}

ServiceInjected.service.ts

ServiceInjected.service.ts

@Injectable()
export class ServiceInjected {
    constructor() {}
    public configure() {
    /*Some actions*/
    }

}

借助这些服务,现在我编写我的单元测试:

With these services, now I write my unit test:

const serviceInjectedStub = {
  configure(): void {}
}


describe('ServiceToTest service Test', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ServiceToTest ,
        { provide: ServiceInjected, useValue: serviceInjectedStub }]
    });
  });

  it('should be initialize the service injected', inject([ServiceToTest],
    (tService: ServiceToTest) => {
      spyOn(serviceInjectedStub, 'configure');
      tService.init();
      expect(serviceInjectedStub.configure).toHaveBeenCalled();
    }));

我希望我的测试会是阳性的,但是我收到以下错误:

I expected my test to be positive, however I receive the following error:

预期的间谍配置已被调用.

Expected spy configure to have been called.

另一方面,如果我以这种方式将注入的服务设置为公共,则可以正常工作:

On the other hand, it works OK if I set the injected service public in this way:

private _si: ServiceInjected by public si: ServiceInjected

推荐答案

您不会监视与TestBed相关的服务.从您的测试平台上获得服务

You don't spy on the service tied to your TestBed. Get the service from your Testbed

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [ServiceToTest ,
      { provide: ServiceInjected, useValue: serviceInjectedStub }]
  });
  injectedService = TestBed.get(ServiceInjected);
});

并对其进行测试

spyOn(injectedService, 'configure').and.returnValue(/* return same data type here */);
// ...
expect(injectedService.configure).toHaveBeenCalled();

这篇关于使用Jasmine angular2注入的私有服务进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:26