13

我正在使用 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() 的对象

4

2 回答 2

13

使用 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
    });
});
于 2016-10-18T13:26:17.883 回答
9

这是由于在 beforeEach 中没有声明

angular 10 之后更新的语法

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

在角度 10 之前

beforeEach(() => {
    slimLoadingBarService = TestBed.get(SlimLoadingBarService);
});
于 2019-05-01T16:28:33.630 回答