如何在不通过测试的情况下获得Jest toThrow的覆盖范围 [英] How to get coverage for Jest toThrow without failing test

查看:854
本文介绍了如何在不通过测试的情况下获得Jest toThrow的覆盖范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用jest --coverage测试以下React组件:

Let's say I'm testing the below React component with jest --coverage:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    if (props.invalid) {
      throw new Error('invalid')
    }
  }
}

覆盖率报告将指出未找到行throw new Error('invalid').由于.not.toThrow()似乎没有涵盖任何内容,因此我用酶创建了以下测试:

the coverage report will say that the line throw new Error('invalid') is uncovered. Since .not.toThrow() doesn't seem to cover anything I create the below test with Enzyme:

const wrapper = shallow(
  <MyComponent invalid />
)

it('should throw', () => {
  function fn() {
    if (wrapper.instance().props.invalid) {
      throw new Error('invalid')
    }
  }
  expect(fn).toThrow()
})

该行被覆盖!但是测试本身失败,并显示encountered a declaration exception-意味着原始组件抛出了错误(应该如此)吗?

and the line gets covered! However the test itself fails with encountered a declaration exception - meaning the original component threw the error (as it should)?

我使用 toThrow() 错误吗?

Am I using toThrow() wrong?

推荐答案

意识到这是一个老问题,但是对于将来的观众来说,我认为我会扩展@galki的答案.除了使用try/catch之外,您还可以简单地将shallow/mount包装在一个匿名函数中,然后使用.toThrowError():

Realise this is an old question, but for future viewers, I thought I'd expand on @galki's answer. Rather than using a try/catch, you could simply wrap your shallow/mount in an anonymous function and then use .toThrowError() instead:

const TestComponent = () => {
    throw new Error('Test error');
}

describe('Test Component', () => {
    it('Throws an error', () => {
        expect(() => shallow(<TestComponent />)).toThrowError();
    });
});

这为您提供了更简洁的代码,并且结果相同.

This gives you much cleaner code, with the same result.

这篇关于如何在不通过测试的情况下获得Jest toThrow的覆盖范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆