Testing with Callbacks

Learn how to use Jest to test asynchronous code with callbacks.

The callback pattern

A callback is a function that is passed as the last argument to another function and called at the end of that function. It looks something like this:

function logger(str) {
  console.log(str);
}

function getUserName(user, callback) {
  const { name } = user;

  callback(name);
}

getUserName(u, logger);

Callbacks and Jest

We can use Jest to test functions that use callbacks to manage asynchronous code. To do this, we can create the callback in our test and then pass it to our asynchronous function. We just have to ensure that we are following best practices on how we compose these tests.

The wrong way

It may be our instinct to just assert at the end of the callback, as depicted in the code below:

Get hands-on with 1400+ tech skills courses.