Write your first test
This guide will instruct you through installing and setting up the @cloudflare/vitest-pool-workers
package. This will help you get started writing tests against your Workers using Vitest. The @cloudflare/vitest-pool-workers
package works by running code inside a Cloudflare Worker that Vitest would usually run inside a Node.js worker thread ↗. For examples of tests using @cloudflare/vitest-pool-workers
, refer to Recipes.
Prerequisites
-
Open the root directory of your Worker or create a new Worker.
-
Make sure that your Worker is developed using the ES modules format. To migrate from the service worker format to the ES modules format, refer to the Migrate to the ES modules format guide.
-
In your project’s
wrangler.toml
configuration file, define a compatibility date of2022-10-31
or higher, and includenodejs_compat
in your compatibility flags.
Install Vitest and @cloudflare/vitest-pool-workers
Open a terminal window and make sure you are in your project’s root directory. Once you have confirmed that, run:
The above commands will add the packages to your package.json
file and install them as dev dependencies.
Define Vitest configuration
If you do not already have a vitest.config.js
or vitest.config.ts
file, you will need to create one and define the following configuration.
You can reference a wrangler.toml
file to leverage its main
entry point, compatibility settings, and bindings.
Add configuration options via Miniflare
Under the hood, the Workers Vitest integration uses Miniflare ↗, the same simulator that powers wrangler dev
’s local mode. Options can be passed directly to Miniflare for advanced configuration.
For example, to add bindings that will be used in tests, you can add miniflare
to defineWorkersConfig
:
This configuration would add a KV namespace TEST_NAMESPACE
that was only accessible in tests. Using this method, you can add or override existing bindings like Durable Objects or service bindings.
Define types
If you are using TypeScript, you will need to define types for Cloudflare Workers and cloudflare:test
to make sure they are detected appropriately. Add a tsconfig.json
in the same folder as your tests (that is, test
) and add the following:
Save this file, and you are ready to write your first test.
Write tests
If you created a basic Worker via the guide listed above, you should have the following fetch handler in the src
folder:
This Worker receives a request, and returns a response of "Hello World!"
. In order to test this, create a test
folder with the following test file:
Add functionality to handle a 404
path on the Worker. This functionality will return the text Not found
as well as the status code 404
.
To test this, add the following to your test file:
Related resources
@cloudflare/vitest-pool-workers
GitHub repository ↗ - Examples of tests using the@cloudflare/vitest-pool-workers
package.