David Angarita
David Angarita

Reputation: 910

Uncaught TypeError: Cannot read property 'filter' of undefined thrown Unit Testing Jasmine

I have this error in unit testing with jasmine:

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

My function:

info() {
  this.requestService.postRequest('Reports', 'getInfo', {})
   .subscribe(
    data => {
      this.places = data.places;
      this.types = data.types.filter(obj => obj.id != 20);
      this.loading = false;
    },
    error => {
      console.log(error);
      this.loading = false;
    });
  };

The test:

it('When call requestService.postRequest', () => {
  
  spyOn(component.requestService, 'postRequest').and.returnValue(of({}));
  
  component.info();
  
  expect(component.requestService.postRequest).toHaveBeenCalled();
  expect(component.requestService.postRequest).toHaveBeenCalledTimes(1);
});

Upvotes: 2

Views: 1899

Answers (1)

Matt U
Matt U

Reputation: 5118

The data object doesn't appear to have a types property (or a places property for that matter. It looks like you need to change

spyOn(component.requestService, 'postRequest').and.returnValue(of({}));

to

spyOn(component.requestService, 'postRequest').and.returnValue(of({
  places: [],
  types: []
}));

Upvotes: 1

Related Questions