spyOn 找不到用于监视 start() 的对象

spyOn could not find an object to spy upon for start()(spyOn 找不到用于监视 start() 的对象)
本文介绍了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() 的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)