Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda