DEV Community

Aditya Kappagantula
Aditya Kappagantula

Posted on

Mock API / Fetch Request

Delay

When writing integration tests or during initial phases of development when APIs are not ready yet, we need to mock an API request that involves adding a delay to the response. Here is an example of the same:


/**
 * @function delay
 * @param {Object} data - any data that needs to be returned
 * @param {Number} ms - time delay in milliseconds
 * @return {Promise<Object>} data
 */
const delay = (data, ms = 1000) => {
  return new Promise(resolve => {
     return setTimeout(resolve(data), ms)
  }) 
}

const apiResponse = [ { a: 1, b: 2 }, { a: 3, b: 4 } ]
const delay(apiResponse).then(result => {
   console.log(result) // prints `apiResponse` after 1 second
})

const result = await delay(apiResponse, 5000)
console.log(result) // prints `apiResponse` after 5 seconds

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
manchicken profile image
Mike Stemle

This is a pretty neat way of mocking out the delays in network traffic. Have you worked with Jest at all? I wonder if you could combine your stuff to make a reusable module which would more fully mock out an API call over the network.