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.
Testing Workers within our Workers runtime can be challenging and requires additional manual setup. Our Workers Vitest integration simplifies this process for most projects. For more details on features and setup instructions, see the Vitest integration Get Started guide.
- Recipes - Examples of unit tests using the Workers Vitest integration.