问题描述
我在尝试对 Angular 服务进行单元测试时遇到问题.我想验证此服务是否正确调用了注入其中的另一个服务.
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.
假设我有这个注入 ServiceInjected 的 ServiceToTest:
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.
另一方面,如果我以这种方式将注入的服务设置为 public 则可以正常工作:
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 注入私有服务的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!