1

I have this function:

function sleep(milliseconds) {
  return new Promise((resolve) => {
    setTimeout(resolve, milliseconds);
  });
}

Basically this function delays logic, e.g.:

function sleep(milliseconds) {
  return new Promise((resolve) => {
    setTimeout(resolve, milliseconds);
  });
}

async function delayedGreeting() {
  console.log("Hello");
  
  await sleep(2000); //will wait 2 Seconds and after that will display the next code
  
  console.log("World!");
}

delayedGreeting();

I want to test the sleep function using Jest.

test('test', async () => {
  await sleep(2000);
});

I don't know how to test this function.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Asking
  • 3,487
  • 11
  • 51
  • 106
  • 1
    You will probably want to record the time before and after the `await sleep` and assert that the difference in time falls within acceptable ranges. If it falls in acceptable ranges. – async await Nov 23 '21 at 18:41
  • 3
    Please do research before asking, Asking: https://stackoverflow.com/q/52673682/3001761 (not even the first time it's asked _today_: https://stackoverflow.com/q/70079395/3001761). – jonrsharpe Nov 23 '21 at 18:41

0 Answers0