Jasmine 单元测试在与所有测试一起运行时失败,在单独运行时成功



我有一个角度 8 项目,并且有一个基本的开箱即用的"应该创建"单元测试失败,并显示错误"未捕获的类型错误:无法读取空抛出的属性'forEach'"。问题是,如果单独运行,则此测试成功,但在与项目的所有其他单元测试一起运行时失败。此外,在单元测试中创建的组件不包含任何 forEach 函数。

有问题的规格

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SubheaderComponent } from './subheader.component';
import { requiredTestModules } from '../../testing/import.helpers';
import { ApplicationInsightsService } from '../../services/application-insight/app-insight.service';
describe('SubheaderComponent', () => {
let component: SubheaderComponent;
let fixture: ComponentFixture<SubheaderComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SubheaderComponent ],
imports: [
requiredTestModules
],
providers: [ApplicationInsightsService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SubheaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

使用 forEach 代码的未实现其他组件:

组件.ts

console.log(selectedInvoices);
this.selectedInvoices = selectedInvoices;
let subtotal = 0;
this.selectedInvoices.forEach((selectedInvoice) => {
subtotal = +subtotal + +selectedInvoice.paymentAmt;
});
this.Subtotal =  subtotal;
this.fee = this.feePercent / 100 * this.Subtotal;
this.totalPayment = this.Subtotal + this.fee;
console.log(this.selectedInvoices);

我确实有其他组件使用 forEach,但达到 forEach(( 的单元测试在隔离和运行所有组件中都成功。

任何帮助/建议将不胜感激。

看起来导致错误的 forEach 在组件测试中被调用,然后再调用失败的 forAdo。添加空检查会使我的测试成功。

更新的组件.ts代码:

if (this.selectedInvoices) {
this.selectedInvoices = selectedInvoices;
let subtotal = 0;
this.selectedInvoices.forEach((selectedInvoice) => {
subtotal = +subtotal + +selectedInvoice.paymentAmt;
});
this.Subtotal =  subtotal;
this.convenienceFee = this.convenienceFeePercent / 100 * this.Subtotal;
this.totalPayment = this.Subtotal + this.convenienceFee;
console.log(this.selectedInvoices);
}

如果针对与错误存在的位置不同的组件抛出错误,似乎很难调试,但这听起来像是一个更大的业力问题。感谢@Archit加格的帮助。

最新更新