首页 > 解决方案 > Jasmine 单元测试用例引发错误,因为无法读取 null 的属性“id”

问题描述

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

用户.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";

 }

用户.spec.ts

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

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

}

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

标签: angularunit-testingjasmine

解决方案


你需要在你的测试中保持逻辑,例如让我们跟随你的测试

  1. 你设置的值this.userObj
 component.userObj = { "id": "123" , "name":"xyz" ,"age":25}
  1. 然后你打电话mapRequest()
component.mapRequest();
  1. 上面的第 3 步设置了this.userObj
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);
 })

}

推荐阅读