Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda