Search code examples
javascriptasynchronoussettimeout

How to mock a delay in my api call function?


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");
  }
};


Solution

  • You can create a simple sleep function.

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

    And then use like

     await sleep(2000);