0
0
Node.jsframework~5 mins

Testing async code in Node.js

Choose your learning style9 modes available
Introduction

Testing async code helps make sure your program works correctly when doing tasks that take time, like reading files or fetching data from the internet.

When you want to check if a function that waits for data returns the right result.
When you need to test code that uses timers or delays.
When your code calls APIs or databases and you want to verify the responses.
When you want to catch errors that happen during asynchronous operations.
When you want to make sure your async code runs in the right order.
Syntax
Node.js
test('description', async () => {
  const result = await asyncFunction();
  expect(result).toBe(expectedValue);
});

Use async before the test function to write asynchronous tests.

Use await to wait for the async operation to finish before checking results.

Examples
This test waits for fetchData to finish and checks if the returned object has an id property.
Node.js
test('fetches data successfully', async () => {
  const data = await fetchData();
  expect(data).toHaveProperty('id');
});
This test checks if the async function throws an error when given bad input.
Node.js
test('throws error on bad input', async () => {
  await expect(asyncFunction('bad')).rejects.toThrow('Invalid input');
});
This test waits for a delay function and checks if at least 1 second passed.
Node.js
test('delays for 1 second', async () => {
  const start = Date.now();
  await delay(1000);
  const end = Date.now();
  expect(end - start).toBeGreaterThanOrEqual(1000);
});
Sample Program

This test checks that fetchData returns an object with the correct properties after waiting 500 milliseconds.

Node.js
import { test, expect } from '@jest/globals';

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ id: 1, name: 'Test' });
    }, 500);
  });
}

test('fetchData returns object with id', async () => {
  const data = await fetchData();
  expect(data).toHaveProperty('id');
  expect(data.id).toBe(1);
  expect(data.name).toBe('Test');
});
OutputSuccess
Important Notes

Always use await with async functions in tests to avoid false positives.

Use rejects to test for errors in async functions.

Keep async tests fast by avoiding unnecessary delays.

Summary

Async tests use async and await to handle waiting.

Use expect to check results after async calls.

Test both success and error cases for async code.