Error is thrown but Jest's `toThrow()` does not capture the error

Viewed 10784

Here is my error codes:

 FAIL  build/__test__/FuncOps.CheckFunctionExistenceByString.test.js
  ● 
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();


    Function FunctionThatDoesNotExistsInString does not exists in string.

      at CheckFunctionExistenceByStr (build/FuncOps.js:35:15)
      at Object.<anonymous> (build/__test__/FuncOps.CheckFunctionExistenceByString.test.js:12:51)
          at new Promise (<anonymous>)
          at <anonymous>

As you can see the error did indeed occurred: Function FunctionThatDoesNotExistsInString does not exists in string.. However it is not captured as a pass in Jest.

Here is my codes:

test(`
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  `, () => {
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  }
);
4 Answers

expect(fn).toThrow() expects a function fn that, when called, throws an exception.

However you are calling CheckFunctionExistenceByStr immediatelly, which causes the function to throw before running the assert.

Replace

test(`
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  `, () => {
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  }
);

with

test(`
    expect(() => {
      CheckFunctionExistenceByStr(
        'any string', 'FunctionThatDoesNotExistsInString'
      )
    }).toThrow();
  `, () => {
    expect(() => {
      CheckFunctionExistenceByStr(
        'any string', 'FunctionThatDoesNotExistsInString'
      )
    }).toThrow();
  }
);

Jest needs a callback function here. Instead of passing the function definition like this:

expect(yourFunction(args)).toThrow(ErrorTypeOrErrorMessage)

Do this:

expect(() => yourFunction(args)).toThrow(ErrorTypeOrErrorMessage)

And for asynchronous functions:

expect(async () => await yourFunction(args)).toThrow(ErrorTypeOrErrorMessage)

had a similar issue but my function to be tested is async and hence your expect have to look like this:

await expect(async () => {await myFunctionToBeTested();}).rejects.toThrow('My Error message')

the solution I got from here

Note:

the await before expect I added 'cause Eslint was complaining but would work without it.

For me, the problem was that the function I was testing was a getter that was immediately executed even when omitting the (). Wrapping the getter in a closure (() => {myClass.get}) fixed the problem.

Related