首页 > 解决方案 > 使用 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 块并给我全面覆盖。我在这里做错了什么。

任何帮助表示赞赏。

标签: javascriptjestjs

解决方案


尝试将抛出异常的代码包装在一个函数中:

expect(() => {
   const model = new Sample(resolvedSample)
}).toThrow(TypeError);

推荐阅读