mock api call with promised settimeout

2020-01-16

 | 

~1 min read

 | 

116 words

I was recently working on a project where I wanted a loading state while an API resolved.

Instead of testing with a live API, I wanted to be able to mock it.

An easy way to do that is to create a simple waitFor function that returns a Promise of a setTimeout. Then, await it.

For example:

const waitFor = (ms) => new Promise((r) => setTimeout(r, ms))

const onClick = async (event) => {
  await waitFor(1000)
  //normal handling of event
}

Now, we can see what the UI does for 1000ms instead of actually making the call. And, if we want, we can use that time to freeze the UI by running the debugger.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!