找不到一个对象来监视start()

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

本文关键字:start 监视 一个对象 找不到      更新时间:2023-09-26

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

但是它不工作。

抛出以下错误:

无法找到一个对象来监视start()

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

这是由于beforeEach

未声明所致

在angular 10之后更新了语法

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

before angular 10

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