Bhu*_*kar 8 javascript jasmine typescript angular2-testing angular
我正在使用angular-cli测试框架.
在我的组件中,我使用了'ng2-slim-loading-bar'节点模块.
submit(){
this._slimLoadingBarService.start(() => {
});
//method operations
}
Run Code Online (Sandbox Code Playgroud)
现在当我测试这个组件时,我已经将spyOn这个服务应用于:
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
});
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
它抛出以下错误:
spyOn无法找到一个窥探start()的对象
这是由于在 beforeEach 中未声明
beforeEach(() => {
slimLoadingBarService = TestBed.get(SlimLoadingBarService);
});
Run Code Online (Sandbox Code Playgroud)
使用let 声明slimLoadingBarService,将其范围限制为beforeEach回调范围。用var声明,或者更好,在适当的describe()块之后声明它,并在beforeEach回调函数中设置其内容:
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
});
});
Run Code Online (Sandbox Code Playgroud)