Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
  }
);
like image 655
notalentgeek Avatar asked Nov 20 '17 16:11

notalentgeek


People also ask

What type of error is thrown if the test fails?

In this case, the test will fail because the WebDriver could not find the element. In this case, StaleElementReferenceException will be thrown.

How do you catch errors in jest?

Testing try catch errors We have a mock function and we want to test whether it throws the error we are expecting. We can do this by simply passing the function to the expect without actually invoking it, and calling the toThrow method on it with the passed error.


2 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();
  }
);
like image 101
Maluen Avatar answered Sep 24 '22 19:09

Maluen


Yeah, this is just Jest being weird. Instead of doing:

expect(youFunction(args)).toThrow(ErrorTypeOrErrorMessage)

Do this:

expect(() => youFunction(args)).toThrow(ErrorTypeOrErrorMessage)
like image 45
leonheess Avatar answered Sep 26 '22 19:09

leonheess