spyOn 找不到用于监视 start() 的对象 [英] spyOn could not find an object to spy upon for start()

查看:14
本文介绍了spyOn 找不到用于监视 start() 的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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() 的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆