Home > Mobile >  Jest: function that should throw does not pass and test will fail
Jest: function that should throw does not pass and test will fail

Time:12-18

I want to test a function A that calls multiple other functions inside it which can throw errors.

Here is an abstraction of my code:

// file A.ts

const A = (args: any[]): boolean => {

   (() => {
      // nested function which throws
      throw new RangeError("some arg not correct")
   })()

   return true
}

and

// file main.test.ts

test("should throw an error", () => {

   expect(A()).toThrow()

})

How do I test this appropriately in Jest?

The test won't succeed and jest will log the thrown error. Here is a enter image description here

CodePudding user response:

I'm not good with typescript so I have written the examples using regular JS.

It turns out you do not need to call the A function to test if it throws:

// throw.test.js
const A = () => {
  (() => {
    // nested function which throws
    throw new RangeError("some arg not correct")
  })();
};


test("should throw an error", () => {
  expect(A).toThrow();
})

which outputs

> jest
 PASS  ./throw.test.js
  ✓ should throw an error (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.404s
Ran all test suites.

If you do want to call the function, say to pass an argument, call it within another function that's passed to the expect:

// throw2.test.js
const A = () => {
  (() => {
    // nested function which throws
    throw new RangeError("some arg not correct")
  })();
};


test("should throw an error", () => {
  expect(() => A('my-arg')).toThrow();
})
  • Related