angular - 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”。我正在学习编写测试用例,所以请纠正这里的错误
解决方案
你需要在你的测试中保持逻辑,例如让我们跟随你的测试
- 你设置的值
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')
空
- 现在您尝试访问
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);
})
}
推荐阅读
- typescript - 在打字稿中为每个函数类型设置参数类型的简单方法
- python - 无法移动或调整 Anaconda Navigator 窗口的大小
- python-3.x - 为什么opencv阈值会在一个非常简单的图像上返回荒谬的输出?
- ios - 是否有任何限制,服务的 BLE 外围设备及其在 iOS swift 中的特性?
- python - 如何标准化我的数据框,以使我的线图从同一点开始?
- select - 选择文件响应 APDU
- ssl - Apache2 SSL 问题:从 zerossl.com 生成免费 SSL,但找不到密钥文件,那么如何使用 certificate.crt 文件创建它?
- react-native - 无法解析模块@react-navigation/stack
- node.js - 如何在 Web 应用程序中集成 Microsoft Project Dashboard?
- r - 如何在 keras 包中定义 lstm、单位、滞后和批量大小