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

275
Vistas
Testing a promise reject code path with jest

I have a situation where I'm trying to test the code path when a promise rejects. The setup is relatively complicated but I've reduced it down to what is a minimum reproducible example:

let resolver;
let rejecter;

const p = new Promise((resolve, reject) => {
    resolver = resolve;
    rejecter = reject;
});

const f = jest.fn((x) => {
    console.log(x);
});

const run = () => {
    return p
        .then(() => {
            f("resolved");
        })
        .catch(() => {
            f("rejected");
        });
};

beforeEach(() => {
    f.mockClear();
});

// this test passes
test("it should call with resolved when p resolves", async () => {
    run();
    resolver();
    await p;

    expect(f).toHaveBeenCalledWith("resolved");
});

// this test fails
test("it should call with rejected when p rejects", async () => {
    run();
    rejecter();
    await p;

    expect(f).toHaveBeenCalledWith("rejected");
});

My problem is that, despite the fact that f is indeed called with "rejected", the test fails, with the reason

thrown: undefined

My guess at this point is that it has something to do with the fact the promise is rejecting; I had hoped this wouldn't be an issue as it's caught. How can I have this test complete sucessfully?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I fixed this by adding a catch onto the promise p:

// this test fails
test("it should call with rejected when p rejects", async () => {
    run();
    rejecter();
    await p.catch(() => {});

    expect(f).toHaveBeenCalledWith("rejected");
});
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