Skip to content
Advertisement

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

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();
  }
);

Advertisement

Answer

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();
  }
);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement