Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

328
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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();
})
about 4 years ago · Juan Pablo Isaza Report

0

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");
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!