lundi 6 juillet 2020

Karma failing tests at random in Angular 8

I'm trying to test an application in Angular 8 but Karma fails random test at random times. Here's the code of a test:

describe('ListiniService', () => {
  let injector: TestBed;
  let service: ListiniService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ListiniService]
    });
    injector = getTestBed();
    service = injector.get(ListiniService);
    httpMock = injector.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  describe('#PriceApi', () => {
    it('it should return an apiPriceList json', () => {
      const apiID = `03020c58-798c-4ad6-8934-45f2c5155f57`;
      const dummyApiPriceList = {
        data: {
            apiPriceList: [
                {
                    action: null,
                    apiId: '03020c58-798c-4ad6-8934-45f2c5155f57',
                    bankId: '96099086-5d1b-4380-ad88-d7b1ecaa44bd',
                    groupId: '15'
                }
            ]
        }
      };
      service.priceApi(apiID).subscribe((response) => {
        expect(response.data.apiPriceList[0].apiId).toEqual(apiID);
      });

      const req = httpMock.expectOne(`/api/priceApi/${apiID}`);
      expect(req.request.method).toBe('GET');
      req.flush(dummyApiPriceList);
    });

The error I get in this case is:

Uncaught TypeError: Cannot read property 'apiPriceList' of undefined thrown

Other times, in other test (again, this is completely random) i get errors like

Uncaught TypeError: Cannot read property 'cod3nFilter' of undefined thrown
Uncaught TypeError: Cannot read property '0' of undefined thrown
Uncaught TypeError: Cannot read property 'length' of undefined thrown

I think I have to do something in the afterEach to "reset" the environment, but I don't know what...

Can somenone help me?

Aucun commentaire:

Enregistrer un commentaire