Create a custom delay for testing

The easiest way to mock an API call operation is to create an delay function that takes some time.

Something like this:

const delay = 
    (delay: number) => await new Promise((resolve, reject) => setTimeout(resolve, delay));

The reason we wrapped the setTimeout in a Promise is because the setTimeout is not a Promise but a callback. This is the old Node API.

However, Node v16+ gives us a Promise version of setTimeout that can be awaited:

import { setTimeout } from "timers/promises"
 
const delay = (delay: number) => await setTimeout(delay)

This is way much easier.

Note:

  • The second way is not supported in the browser, only in a Node environment.
  • To avoid issues and if using both environments (client and server), use the first way.