Skip to content

Testing Asynchronous Code

Medium ~40 min

What you'll build

An async data processing module with functions using Promises, async/await, and callbacks, plus a complete test suite covering all async patterns.

Goals

  • Test async/await functions correctly
  • Test Promise-based functions by returning them
  • Test callback-based functions using the done callback
  • Test rejected promises with .rejects
  • Handle timing with fake timers

Prerequisites

  • Completed Project 1 or equivalent Jest experience
  • Understanding of Promises and async/await
  • Familiarity with callbacks

Steps

  1. 1

    Create the async module

    Create asyncProcessor.js with functions using different async patterns.

    Code
    // Promise-based
    function fetchUserData(userId) {
      return new Promise((resolve) => {
        setTimeout(() => resolve({ id: userId, name: 'User' + userId }), 100);
      });
    }
    
    // async/await
    async function processUser(userId) {
      const user = await fetchUserData(userId);
      return { ...user, processed: true };
    }
    
    // Callback-based
    function loadData(callback) {
      setTimeout(() => callback(null, 'loaded'), 50);
    }
    module.exports = { fetchUserData, processUser, loadData };

    Expected result

    asyncProcessor.js is created with three async functions.

  2. 2

    Test async/await functions

    Create asyncProcessor.test.js. Test processUser using async/await in the test callback.

    Code
    const { processUser } = require('./asyncProcessor');
    
    test('processUser returns processed user', async () => {
      const result = await processUser(1);
      expect(result).toEqual({ id: 1, name: 'User1', processed: true });
    });

    Expected result

    Async test passes.

  3. 3

    Test by returning promises

    Test fetchUserData by returning the promise from the test (alternative to async/await).

    Code
    const { fetchUserData } = require('./asyncProcessor');
    
    test('fetchUserData returns user data', () => {
      return fetchUserData(2).then(data => {
        expect(data).toEqual({ id: 2, name: 'User2' });
      });
    });

    Expected result

    Promise-based test passes.

  4. 4

    Test callback functions with done

    Test loadData using the done callback pattern.

    Code
    const { loadData } = require('./asyncProcessor');
    
    test('loadData calls callback with data', (done) => {
      loadData((err, data) => {
        expect(err).toBeNull();
        expect(data).toBe('loaded');
        done();
      });
    });

    Expected result

    Callback test passes.

  5. 5

    Use fake timers for speed

    Add fake timers to avoid waiting for real timeouts. Use jest.useFakeTimers() and jest.advanceTimersByTime().

    Code
    beforeEach(() => jest.useFakeTimers());
    afterEach(() => jest.useRealTimers());
    
    test('processUser works with fake timers', async () => {
      const promise = processUser(3);
      jest.advanceTimersByTime(100);
      const result = await promise;
      expect(result.processed).toBe(true);
    });

    Expected result

    Test passes instantly without real waiting.

Try it yourself

What you learned

You learned three ways to test async code: async/await in test callbacks, returning promises, and the done callback. You also learned to use fake timers to control time in tests, making them fast and deterministic.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic