Angular Jasmine单元测试用例抛出错误,因为无法读取属性';id';空的

Angular Jasmine单元测试用例抛出错误,因为无法读取属性';id';空的,angular,unit-testing,jasmine,Angular,Unit Testing,Jasmine,我正在为一个方法编写测试用例,该方法将一个对象映射到具有类似属性的另一个对象 user.ts mapRequest(){ const common_property =["id","name","age"]; this.req= {}; this.userObj = JSON.parse(window.localStorage.getItem('userObj')); common_property.forEac

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

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";

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

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

}
用户规范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";

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

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

}

虽然我为userObj对象设置了映射到req obj的值,但由于无法读取null的属性“id”,所以出现了错误。我正在学习编写测试用例,因此请纠正此处的错误

您需要在测试中保持逻辑性,例如让我们关注您的测试

  • 您可以设置this.userObj的
  • component.userObj={“id”:“123”,“name”:“xyz”,“age”:25}
    
  • 然后调用
    mapRequest()
  • component.mapRequest();
    
  • 上面的步骤3设置
    this.userObj
  • this.userObj=JSON.parse(window.localStorage.getItem('userObj');
    
    但是
    window.localStorage.getItem('userObj')
    的值将为null

  • 现在您尝试访问
    this.userObj[item]
    ,它为空,因此出现错误
  • 解决方案

    试试下面

    it('应该调用mapRequest',()=>{
    spyOn(window.localStorage,'getItem').and.returnValue({“id”:“123”,“name”:“xyz”,“age”:25})
    mapRequest();
    expect(component.userObj.id).toBe(123);
    })
    }
    
    您需要在测试中保持逻辑性,例如让我们跟随您的测试

  • 您可以设置this.userObj的
  • component.userObj={“id”:“123”,“name”:“xyz”,“age”:25}
    
  • 然后调用
    mapRequest()
  • component.mapRequest();
    
  • 上面的步骤3设置
    this.userObj
  • this.userObj=JSON.parse(window.localStorage.getItem('userObj');
    
    但是
    window.localStorage.getItem('userObj')
    的值将为null

  • 现在您尝试访问
    this.userObj[item]
    ,它为空,因此出现错误
  • 解决方案

    试试下面

    it('应该调用mapRequest',()=>{
    spyOn(window.localStorage,'getItem').and.returnValue({“id”:“123”,“name”:“xyz”,“age”:25})
    mapRequest();
    expect(component.userObj.id).toBe(123);
    })
    }
    
    spyOn window.localstorage抛出错误,因为string类型的参数不可分配给neverPlease check类型的参数,我已删除
    'window.localstorage'
    spyOn window.localstorage抛出错误,因为string类型的参数不可分配给neverPlease check类型的参数,我已经删除了
    'window.localStorage'