問題描述
我正在使用 angular-cli 測試框架.
I am using angular-cli testing framework.
在我的組件中,我使用了ng2-slim-loading-bar"節點模塊.
inside my component , I have used 'ng2-slim-loading-bar' node module.
submit(){
this._slimLoadingBarService.start(() => {
});
//method operations
}
現在當我測試這個組件時,我已經將 spyOn 這個服務應用為:
Now when I am testing this component, I have applied spyOn this service as :
beforeEach(() => {
let slimLoadingBarService=new SlimLoadingBarService();
demoComponent = new DemoComponent(slimLoadingBarService);
TestBed.configureTestingModule({
declarations: [
DemoComponent
],
providers: [
{ provide: SlimLoadingBarService, useClass: SlimLoadingBarService}
],
imports: [
SharedModule
]
});
});
it('should pass data to servie', () => {
spyOn(slimLoadingBarService,'start').and.callThrough();
//testing code,if I remove the above service from my component, test runs fine
});
但它不起作用.
它拋出以下錯誤:
spyOn 無法為 start() 找到要監視的對象
spyOn could not find an object to spy upon for start()
推薦答案
使用 let 聲明 slimLoadingBarService,您將其范圍限制為 beforeEach 回調范圍.用 var 聲明它,或者更好的是,在正確的 describe() 塊之后聲明它,并在 beforeEach 回調函數中設置它的內容:
Declaring slimLoadingBarService with let, you are constraining its scope to the beforeEach callback scope. Declare it with var, or better, declare it after the proper describe() block and set its content within beforeEach callback function:
describe("some describe statement" , function(){
let slimLoadingBarService = null;
beforeEach( () => {
slimLoadingBarService=new SlimLoadingBarService();
});
it('should pass data to service', () => {
spyOn(slimLoadingBarService,'start').and.callThrough();
//testing code,if I remove the above service from my component, test runs fine
});
});
這篇關于spyOn 找不到用于監視 start() 的對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!