I am running unit test for post API call,I have already verified API is getting called correctly. I get error cannot read property of undefined. I suspect this is problem of asynchronous code.

My API is getting called twice, it takes almost 2000 ms to fulfill the api request. So I have added tick(2500).

Still I get Property not defined when I expect(component.Financials.length).toBe(1);

spec.ts

it('should return one object', fakeAsync(() => {
      var dummyObject : any[];
     dummyObject = [
        {
          account: "shjdhjhs",
          product: "xyz"

        }
      ];
      mockFilter={ account="shjdhjhs"}

      //invoking method and intializing filter data
      compoenent.filter=mockFilter;
      component.Data();
      const req = httpMock.expectOne('/api/getrecords');
      //fails, as this api is called many times
      expect(req.request.method).toBe("POST");
      req.flush( dummyObject);
      tick(2500);
      expect(component.records.length).toBe(1);
      //cannot read property of undefined
      expect(component.records).toEqual( dummyObject);

  }));

ApiCall.ts

Data() {
    this.records = [];

    this.http.post<Device[]>('/api/getrecords', this.filter)
      .subscribe(res => {
        if (res['status'] == "FAILURE") {
          console.log(res);
        } else {
          this.records = res['data'];
          ...
        }
       }

0 Answers