我有一个angular 8项目,并且有一个现成的“应创建”单元测试,但失败了,基本错误,提示“未捕获的TypeError:无法读取抛出的null的属性'forEach'”。问题在于,如果单独运行,此测试将成功,但是与项目的所有其他单元测试一起运行时,该测试将失败。同样,在单元测试中创建的组件不包含任何forEach函数。
有关的问题
scanf("%f", &result); // Not correct
scanf("%lf", &result); // Correct
使用forEach代码未实现的其他组件:
component.ts
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的组件,但是击中那些forEach()的单元测试在隔离和全部运行方面都成功了。
任何帮助/建议将不胜感激。
答案 0 :(得分:0)
看起来像导致错误的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的帮助。