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

85
Views
Verify async function throws non-error object using jest

Using the jest framework, how can I verify that my async function throws something other than an Error?

In my examples below, the first one works as expected, as the function being tested throws an Error. The second example, where the function throws a string, doesnt work - jest doesnt verify that the function throws.

// Works as expected
test('verify error thrown', async () => {
    const expected = new Error('actual-error');
    const fn = async () => { throw expected; };
    await expect(fn()).rejects.toThrow(expected);
});

// Fails with: Received function did not throw
test('verify non-error thrown', async () => {
    const expected = 'non-error';
    const fn = async () => { throw expected; };
    await expect(fn()).rejects.toThrow(expected);
});
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I don't think you need 'rejects' in either case. According to the docs it's not clear if the toThrow method expects results to be derived from Error. There is a regex form which might validate against a string.

rejects says that it unwraps the rejection so it can be matched, and that might give you the error message string from Error, or a string if the result was a string.

about 4 years ago · Juan Pablo Isaza Report

0

Dave's point was absolutely right; using rejects.toThrow was not the right way to go here.

Instead, I'm managed to verify the expected behaviour by simply catching the error and verifying it's value.


test('verify non-error thrown', async () => {
    const expected = 'non-error';
    const fn = async () => { throw expected; };
    await fn().catch(error => expect(error).toStrictEqual(expected));
    expect.assertions(1);
});

Note that expect.assertions(1) is important here. Without this, if the code being tested was updated to not throw, the test would still pass.

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!