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

132
Visualizações
Jest how to test if a mocked promise is waited to be resolved

My application code is something like this:

const promises = requests.map(async request => {await someAPI(request)});
await Promises.all(promises);

I don't care about the return value.

I have a mock for the API like

const someAPI = jest.fn().mockReturnValue(Promise.resolve(true));

I can test that someAPI is called with the right parameters, but how can I test that the returned promise is indeed resolved? For example, if the client code is simply

const promises = requests.map(async request => {await someAPI(request)});

It would pass the test for calling the API, even though it doesn't actually try to resolve the promises.

I tried the suggestion, but this still doesn't work.

    let promiseResolved = false;
    someAPI.mockImplementation(
      () =>
        new Promise((resolve) => {
          promiseResolved = true;
          resolve();
        })
    );

When the method calls

const promises = requests.map(async request => {await someAPI(request)});

The boolean is already set to true. In reality, the API isn't even called if I don't do the Promise.all step.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you declare a local boolean initialized to false, subscribe to the promise and set the boolean true when the promise is resolved, then assert the boolean is true, does this cover the test case?

about 4 years ago · Juan Pablo Isaza Relatório

0

Ok I figured it out! Following @pawooten's suggestion, I created a local boolean variable. However, to make the test fail if the code doesn't wait for the promise to resolve, I had to add an asynchronous element to the mock Promise, like this:

let promiseResolved = false;
someAPI.mockImplementation(
  () =>
    new Promise((resolve) => {
      setTimeout(() => {
        promiseResolved = true;
        resolve();
      }, 1000);
    })
);
expect(promiseResolved).toBe(true)
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