【问题标题】:Unit test Angular 4 getting error `TypeError: Cannot read property 'subscribe' of undefined`单元测试Angular 4出现错误`TypeError:无法读取未定义的属性'订阅'
【发布时间】:2018-07-27 17:32:24
【问题描述】:

我在单元测试中收到错误TypeError: Cannot read property 'subscribe' of undefined,如何解决?

我的部分代码:

规格

 it('makes expected calls', () => {
        const item1: item3 = fixture.debugElement.injector.get(item3);
        spyOn(comp, 'item5');
        spyOn(item1, 'item2');
        comp.item4();
        expect(comp.item5).toHaveBeenCalled();
        expect(item1.item2).toHaveBeenCalled();
    });

如果我删除规范的这一部分,我会成功。

我使用 subscribe() 的方式是否正确?

【问题讨论】:

  • 你能在构造函数中显示 IJ 吗?

标签: javascript angular unit-testing


【解决方案1】:

尝试为为方法isPeriodCycleOpen 创建的间谍提供一个模拟Observable Jasmine spy returnValue,以便为组件提供一些东西以使subscribe 能够:

import { Observable } from 'rxjs/Observable';

it('makes expected calls', () => {
    const mockResponse = { cyclePeriodOpen: true, deadLineCycle: 'foobar' };

    const cycleServiceStub: CycleService = fixture.debugElement.injector.get(CycleService);
    spyOn(comp, 'setChartData');
    spyOn(cycleServiceStub, 'isPeriodCycleOpen').and.returnValue(Observable.of(mockResponse));
    comp.getCycleStatus();
    expect(comp.setChartData).toHaveBeenCalled();
    expect(cycleServiceStub.isPeriodCycleOpen).toHaveBeenCalled();
});

希望对您有所帮助!

【讨论】:

  • 嘿伙计,谢谢你的帮助,在 mockResponse 之后再放一个 ))...我成功了 =D
【解决方案2】:

我认为你缺少 spyon 方法的返回值,试试这个:

it('makes expected calls', () => {
    const cycleServiceStub: CycleService = 
    fixture.debugElement.injector.get(CycleService);
    spyOn(comp, 'setChartData');
    spyOn(cycleServiceStub, 'isPeriodCycleOpen')
        .and.callFake(() => Observable.of('yourValue')});
    comp.getCycleStatus();
    expect(comp.setChartData).toHaveBeenCalled();
            expect(cycleServiceStub.isPeriodCycleOpen).toHaveBeenCalled();
});

【讨论】:

    猜你喜欢
    • 2018-02-14
    • 2019-04-06
    • 2018-11-11
    • 2019-08-06
    • 1970-01-01
    • 2018-02-13
    • 2017-06-28
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多