Why does Jest throw an error when it should not?

纵然是瞬间 提交于 2021-02-05 12:27:26

问题


I have a function like this:

const test = (match) => {
   if (match !== 'cat') {
     throw new TypeError()
   }
}

My test would be:

describe('test', () => {
  it('must throw error'() => {
    try {
      test('cat')
    catch(err){
      expect(err).toStrictEqual(new TypeError())
    }
  }
}

But the test passed. It should fail. Why did it pass?


回答1:


Tests only fail if there is an unmet expectation. In your case, because no error is thrown, no expectation is ever even evaluated. Therefore the test passes.

To deal with this, either:

  1. make sure exactly one expectation is evaluated using expect.assertions:

    describe('test', () => {
      it('must throw error'() => {
        expect.assertions(1);
        try {
          test('cat')
        catch(err){
          expect(err).toStrictEqual(new TypeError())
        }
      }
    }
    

    or

  2. handle the error with a .toThrow expectation rather than catching it yourself:

    describe('test', () => {
      it('must throw error'() => {
        expect(() => test('cat')).toThrow(TypeError)
      }
    }
    

    Note that, as Estus Flask pointed out, this can only assert on either the constructor or the message of the error.



来源:https://stackoverflow.com/questions/64330421/why-does-jest-throw-an-error-when-it-should-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!