Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!