spyOn无法找到一个窥探start()的对象

时间:2016-10-18 11:18:05

标签: javascript angular typescript jasmine angular2-testing

我正在使用angular-cli测试框架。

在我的组件中,我使用了'ng2-slim-loading-bar'节点模块。

submit(){
    this._slimLoadingBarService.start(() => {
    });
    //method operations
}

现在当我测试这个组件时,我已经将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
});

但它不起作用。

它抛出以下错误:

  

spyOn找不到一个窥探start()

的对象

2 个答案:

答案 0 :(得分:4)

使用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
    });
});

答案 1 :(得分:1)

这是由于在beforeEach中未声明

beforeEach(()=>{
 slimLoadingBarService=TestBed.get(SlimLoadingBarService);
}