我如何测试下面我使用类的代码片段中的 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
// 示例.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);
})
})
Run Code Online (Sandbox Code Playgroud)
我应该会失败,然后只有它会到达 catch 块并给我完全覆盖。我在这里做错了什么。
任何帮助表示赞赏。
尝试将抛出异常的代码包装在函数中:
expect(() => {
const model = new Sample(resolvedSample)
}).toThrow(TypeError);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29116 次 |
| 最近记录: |