Skip to content

Unit testing

In a Workers context, a unit test imports and directly calls functions from your Worker. After calling the functions, the unit test then asserts on the functions’ return values. For example, consider you have the following Worker:

export function add(a, b) {
return a + b;
}
export default {
async fetch(request) {
const url = new URL(request.url);
const a = parseInt(url.searchParams.get("a"));
const b = parseInt(url.searchParams.get("b"));
return new Response(add(a, b));
}
}

An example unit test for the above Worker may look like the following:

import { add } from "./index.mjs";
assert(add(1, 2) === 3);

This test only verifies that the add function is returning the correct value, but does not test the Worker itself like an integration test would.

Vitest integration

The recommended way to unit test your Workers is by using the Workers Vitest integration. For more information on features, as well as installation and setup instructions, refer to the Vitest integration Get Started guide.

  • Recipes - Examples of unit tests using the Workers Vitest integration.