使用玩笑测试catch块

时间:2019-03-20 05:48:45

标签: javascript jestjs

我如何在下面使用我的类的代码段中测试catch块

// Sample.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块并给我完整的覆盖范围。我在这里做错什么了。

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

尝试将引发异常的代码包装在函数中:

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

答案 1 :(得分:1)

根据有趣的文档

  

注意:您必须将代码包装在一个函数中,否则错误将不会被捕获并且断言将失败。

参考:https://jestjs.io/docs/en/expect#tothrowerror

describe('Dummy test', () => {
  class Sample {
      constructor(data){
        this.resolvedData = this.retrieveData(data) 
      }

      retrieveData(data){
        try{
          const resolvedData = data.map(o => o.name);
        }catch(error){
          throw error
        }
      }   
  }

  test('should fail', () => {
      expect(() => {
          new Sample({});
      }).toThrowError(TypeError);
  });
});