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

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

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 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