What are the best practices for writing tests for Workers?

Hi everyone,

I’m new to developing Cloudflare Workers and I’m a bit lost.
I’m failing to discover the proper way to write tests.

These blogs posts deal with it: https://blog.cloudflare.com/unit-testing-workers-in-cloudflare-workers/ https://blog.cloudflare.com/unit-testing-worker-functions/ .

The first one offers a way to run tests in the production environment, which I’m quite reluctant to do, to be honest. The second uses a package that is no longer maintained.

I’d like to know if there are some best practices for writing tests for workers. Where should I look for it?

Here are some issues I’m worried about:

  • Import syntax
  • CORS issues
  • Availability of the Web API

You could “split” your worker into two, staging and production.
Use Jest and Fetch to specifically test critical points on your staging worker, after all tests pass you can move it to production.

You could use Cloudflare Access to shield the staging worker from unwanted access.

Rough example below:

const originalFetch = require("isomorphic-fetch");
const fetch = require("fetch-retry")(originalFetch);
const expect = require("expect");

const endpointStatus = async url => {
  const response = await fetch(url, {
    retries: 3,
    retryDelay: 3000,
    redirect: "manual"
  return response.status;

const domains = [...];

domains.forEach(e => {
  test(`200: ${e}`, async () =>
    expect(await endpointStatus(`https://${e}/`)).toBe(200));

  test(`301: www.${e}`, async () =>
    expect(await endpointStatus(`https://www.${e}/`)).toBe(301));

1 Like

Thanks man!

I’m also new to Cloudflare and didn’t know about Cloudflare Access. It seems that it indeed does the trick.
I think I’m going to write some tests that fetch against a wrangler dev in my own machine and some other tests to go a staging worker, as you suggested.
Thanks a lot.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.