【问题标题】:I can't reach the component from the spec file in Angular - Karma/Jasmine unit tests我无法从 Angular 的规范文件中访问组件 - Karma/Jasmine 单元测试
【发布时间】:2021-09-24 18:34:38
【问题描述】:

我正在尝试在 Angular 中运行一个简单的单元测试,但它失败了,我无法从 spect 文件中访问该组件。它说找不到未定义的属性,我无法弄清楚错误在哪里。这是我要测试的组件中的函数:

factorOrQuickpay(): void {
    if (this.load.factor) {
        this.factor = true;
        this.resourceType = TableResources.Factor;
    } else if (!this.load.factor) {
        this.factor = false;
        this.resourceType = TableResources.Quickpay;
    } else if(!this.load.factor && !this.load.quickpay) {
        this.none = true;
    }
}

这是 .spec 文件:

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { LoadResourcesComponent } from './load-resources.component';

describe('LoadResourcesComponent', () => {
    let component: LoadResourcesComponent;
    let fixture: ComponentFixture<LoadResourcesComponent>;

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            declarations: [LoadResourcesComponent],
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(LoadResourcesComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    fdescribe('factorOrQuickpay', () => {
        beforeEach(() => {
            spyOn(component, 'factorOrQuickpay');
        });

        it('shows Factor Load scenario', () => {
            component.factorOrQuickpay()
            expect(component.factor).toBe(true);
        });
    });
});

你能帮我找出错误在哪里吗?

错误信息是“TypeError: Cannot read property 'factor' of undefined.”

谢谢。

【问题讨论】:

  • 删除spyOn(component, 'factorOrQuickpay');。如果您想模拟某些函数行为或分析您的鳕鱼如何调用此函数,则需要间谍。这里没有意义

标签: angular unit-testing karma-jasmine


【解决方案1】:

我认为您的节​​点版本是 15.0。将您的节点版本降级到节点 14.0 即可。

参考这个: https://github.com/karma-runner/karma/issues/3571

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 2015-06-29
    • 2015-12-10
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多