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

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

问题描述

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



在组件内部,我使用了 ng2-slim-loading-bar节点模块。

  submit(){
this._slimLoadingBarService.start(()=> {
});
//方法操作
}

现在,当我测试此组件时,我已将此spyOnOn服务应用为:

  beforeEach(()=> {
let slimLoadingBarService = new SlimLoadingBarService( );
demoComponent = new DemoComponent(slimLoadingBarService);
TestBed.configureTestingModule({
声明:[
DemoComponent
],
提供者:[
{提供:SlimLoadingBarService,useClass:SlimLoadingBarService}
],
导入:[
SharedModule
]
});
});
it('应该将数据传递给servie',()=> {
spyOn(slimLoadingBarService,'start')。and.callThrough();
//测试代码,如果我从我的组件中删除上述服务,测试运行正常
});

但它不起作用。



它抛出以下错误:


spyOn找不到要监视的对象以用作start()



解决方案

使用let声明 slimLoadingBarService ,您会将其范围限制为beforeEach回调范围。用var声明,或者更好,在适当的describe()块之后声明它,并将其内容设置在beforeEach回调函数中:

  describe( some describe statement,function(){
let slimLoadingBarService = null;

beforeEach(()=> {
slimLoadingBarService = new SlimLoadingBarService();

});

it('应该将数据传递给服务',()=> {
spyOn(slimLoadingBarService,'start')。and.callThrough( );
//测试代码,如果我从组件中删除了上述服务,则测试可以正常运行
});
});


I am using angular-cli testing framework.

inside my component , I have used 'ng2-slim-loading-bar' node module.

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

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

but its not working.

It throws below error:

spyOn could not find an object to spy upon for start()

解决方案

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天全站免登陆