'Jest: function that should throw does not pass and test will fail

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 sandbox and here is the output of the test you can see if you run test:

enter image description here



Solution 1:[1]

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

Solution 2:[2]

I refactored a function that was async to no longer be async and was getting this error. So, if you have an inner-async function, use this approach:

test("async function throws", async() => {
    await expect(() => A('my-arg')).rejects.toThrow();
})

You can also do some more specific checks like, what kind of error and the message, etc.

test("async function throws", async() => {
    await expect(() => A('my-arg')).rejects.toThrow(MyError("Specific Error Message");
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 evolutionxbox
Solution 2 tjgragg