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

182
Views
Mock a thrown exception

Is there a way to mock what a thrown exception in the try catch block? I want to test my function that the url string in error.message is indeed replaced with replacedURL string. How can I easily test it or mock the thrown exception to an object with this URL.

async function getUsers() {
  try {
    const response = await fetch('/api/users');

    if (response.status >= 400) {
      console.error('Could not fetch users');
      return;
    }

    const users = response.json();
    return users;
  } catch (error) {
    let message = error.message;
    if (message) {
      message = message.replace(/https:\/\/some.url.com /g, 'replacedURL');
      delete error.message;
    }

    console.error('error', error);
  }
}

Here's my test

test('url in error message is replaced', () => {
  expect(getUsers()).toThrow('replacedURL');
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You might want to actually throw an error in your function for it to be caught by toThrow.

Also, I'd recommend that your test doesn't actually tries fetching from the API (unless you're sure that's what you want it to do). Instead, consider using a custom caller (which can extend fetch) which you can then mock the response for, like const caller = jest.fn().mockRejectedValue({ message: 'https:://some.url.com' });

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!