Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
  }
};
like image 273
DoneDeal0 Avatar asked Dec 17 '22 12:12

DoneDeal0


1 Answers

You can create a simple sleep function.

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

And then use like

 await sleep(2000);
like image 63
Keith Avatar answered Dec 30 '22 19:12

Keith