Search⌘ K
AI Features

Writing Asynchronous Tests

Understand how to write asynchronous tests with Jest by learning to await promises in your test functions. Explore testing of asynchronous functions using async and await keywords to verify expected outcomes in React applications.

Testing an asynchronous function

We are going to write unit tests on the getName function below:

export async function getName(id) {
  await wait(200);
  return names.length <= id ? null : names[id];
}

The getName function is asynchronous and returns a promise of either a name or null. It is asynchronous because of the call to a wait function, which uses setTimeout to resolve a promise after a certain number of milliseconds:

 ...