我有一个角度为8的项目,并且有一个现成的基本版本,“应该创建”单元测试失败,并出现错误“未捕获的TypeError:无法读取抛出的null的属性'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代码未实现的其他组件:
component.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在组件测试之前被调用,而失败了。添加空检查使我的测试成功。
更新后的component.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 Garg的帮助。