Jasmine 单元测试用例抛出错误 Cannot read 属性 'id' of null

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

我正在为将一个对象映射到具有相似属性的另一个对象的方法编写测试用例。

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();
 })

}

尽管我将 userObj 对象的值设置为映射到 req obj,但我收到错误消息,因为无法读取 属性 'id' of null。我正在学习写测试用例所以请纠正这里的错误

您的测试需要符合逻辑,例如让我们跟随您的测试

  1. 你设置的值this.userObj
 component.userObj = { "id": "123" , "name":"xyz" ,"age":25}
  1. 然后你打电话给mapRequest()
component.mapRequest();
  1. 上面的第 3 步设置了 this.userObj
  2. 的值
this.userObj = JSON.parse(window.localStorage.getItem('userObj'));

但是window.localStorage.getItem('userObj')的值将为空

  1. 现在您尝试访问 this.userObj[item],它为空,因此出现错误

解决方案

试试下面

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

}