Jasmine Unit test case throws error as Cannot read property 'id' of null

Viewed 2451

I am writing test case for a method that maps one object to another object that has similar properties.

user.ts

mapRequest(){
   const common_property =["id","name","age"];
   this.req= {};
   this.userObj = JSON.parse(window.localStorage.getItem('userObj'));
   common_property.forEach(item => req[item] = this.userObj[item]);
   this.req.location = "AN";

 }

user.spec.ts

it('should mapRequest called ',done => {

  component.userObj = { "id": "123" , "name":"xyz" ,"age":25}
  component.mapRequest();
  expect(component).toBeTruthy();
  done();
 })

}

though i set the value for userObj Object to get mapped to req obj i am getting error as cannot read property 'id' of null. I am learning to write test case so please correct what is wrong here

1 Answers

You need to be logical in your tests, e.g Lets follow your test

  1. You set the value of this.userObj
 component.userObj = { "id": "123" , "name":"xyz" ,"age":25}
  1. You then call mapRequest()
component.mapRequest();
  1. Step 3 above sets the value of this.userObj
this.userObj = JSON.parse(window.localStorage.getItem('userObj'));

But the value of window.localStorage.getItem('userObj') will be null

  1. Now you try to access this.userObj[item] which is null hence the error

Solution

Try Below

it('should mapRequest called ', () => {
  spyOn(window.localStorage, 'getItem').and.returnValue({ "id": "123" , "name":"xyz" ,"age":25})
  component.mapRequest();
  expect(component.userObj.id).toBe(123);
 })

}
Related