Жасмин Юнит Тест не пройден при запуске со всеми тестами, успешен при изолированной работе - PullRequest
0 голосов
/ 15 октября 2019

У меня есть угловой проект 8, и у меня есть базовый готовый модульный тест «следует создать» с ошибкой «Uncaught TypeError: Невозможно прочитать свойство 'forEach' из null thrown". Проблема в том, что этот тест завершается успешно, если он запускается изолированно, но не проходит при запуске со всеми другими модульными тестами для проекта. Также компонент, который создается в модульном тесте, не содержит никаких функций 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 (), проходят успешно как в отдельности, так и с run all.

Любая помощь / предложения могуточень цениться.

1 Ответ

0 голосов
/ 15 октября 2019

Похоже, что 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 за помощь.

...