How to mock a delay in my api call function?

Viewed 6432

I have a function to update an user with an api post request. The backend is not done yet. The function will thus always return an error. In order to test the loading and error states, I would like to temporarily add a fake delay before returning the result. How to do so? Here is the function:

const updateProfile = async (form) => {
  try {
    const res = await api.post("/update-profile", form);
    return res;
  } catch (err) {
    throw new Error("error.unknown");
  }
};

Writing this didn't work:

const updateProfile = async (form) => {
  try {
    let fakeCallDone = false
    setTimeout(()=> fakeCallDone = true, 2000)
    const res = await api.post("/update-profile", form);
    fakeCallDone && res;
  } catch (err) {
    throw new Error("error.unknown");
  }
};

3 Answers

You can create a simple sleep function.

const sleep = ms => new Promise(
  resolve => setTimeout(resolve, ms));

And then use like

 await sleep(2000);

You can return a new promise in the meantime (Until the backend is ready):

const updateProfile = async () => {
  try {
    // const res = await api.post("/update-profile", form);
    // return res;
    return new Promise((res, rej) => {
     setTimeout(() => res('response'), 2000)
    })
  } catch (err) {
    throw new Error("error.unknown");
  }
};

updateProfile().then(console.log)

The problem is here:

setTimeout(()=> fakeCallDone = true, 2000)

It will move on to Web API then continue to execute the next line codes.

[Solution]

const updateProfile = async (form) => {
  try {
   var res = api.post("/update-profile", form); // this async code will move on `web api`. When it's done will move on to queue.
   await delay(2000); // You mock a delay here
   return await res; // Resolve value from `res` promise. 
  } catch (err) {
    throw new Error("error.unknown");
  }
};

delay() method look like this:

const delay= ms => new Promise(resolve => setTimeout(resolve, ms));

Note: you should get more details about event loop to know

  1. How js works: call stack, web API, queue, event loop
  2. Async programming in Javascript.
Related