Writing Asynchronous Tests

Learn to write and test asynchronous code in this lesson.

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:

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

We also have an array containing two names:

const names = ["Bill", "Jane"];

So, calling getName with 0 or 1 should return the relevant name from the names array.

Get hands-on with 1200+ tech skills courses.