javascript - 使用 jest 测试 catch 块
问题描述
我如何在下面我使用类的代码片段中测试 catch 块
// 示例.js
class Sample{
constructor(data){
this.resolvedData = this.retrieveData(data)
}
retrieveData(data){
try{
const resolvedData = data.map(o => o.name);
}catch(error){
throw error
}
}
}
// Sample.test.js
const Sample = require('./Sample');
describe('Sample File test cases', () => {
test('should return the resolvedData', () => {
const resolvedSample = [{name: "John", id: 123}, {name: "Doe", id: 3432}]
const model = new Sample(resolvedSample);
const expectedResolvedSample = [{name: "John"}, {name: "Doe"}]
expect(model).toEqual(expectedResolvedSample)
})
test('should throw an error', () => {
const resolvedSample = {}
const model = new Sample(resolvedSample) // failing here map method since i am passing an object
expect(model).toThrow(TypeError);
})
})
我应该失败然后只有它会来到 catch 块并给我全面覆盖。我在这里做错了什么。
任何帮助表示赞赏。
解决方案
尝试将抛出异常的代码包装在一个函数中:
expect(() => {
const model = new Sample(resolvedSample)
}).toThrow(TypeError);
推荐阅读
- rxjs - 带有异步函数和 toPromise 的 Observable RxJS 有什么意外行为?
- javascript - 事件未在 socket.on('connect', event) 上调用
- apache - 如何为我的 jira 工具将 http 转换为 https
- javascript - 如何在 GET 方法中检查用户身份验证?
- firebase - 可调用函数支持缓存吗?
- environment-variables - 将 json 重命名为 *.environment.json 并且无法在邮递员中导入相同的内容
- java - 使用带有当前日期和 dob 和枚举的休眠保存学生
- centos - eth1接口在ifconfig中不可见,在centos6中无法与其他服务器交互
- java - 尝试在网站完全打开之前输入登录凭据时出现“无警报打开”
- java - 方法.matches String false,如何匹配true