Testing Cloudflare Workers and Edge Functions

Testing Cloudflare Workers and Edge Functions

Cloudflare Workers run in V8 isolates at the edge, not Node.js. That makes testing them different from testing regular Node services. The environment is sandboxed, the APIs are Web Standards (Fetch, Request, Response, Streams), and bindings for KV, D1, R2, and Durable Objects have no direct equivalent outside of Cloudflare's runtime.

Miniflare and Wrangler's built-in test utilities fill that gap. This guide covers the full testing stack: unit tests with Miniflare, testing each binding type, and end-to-end tests with Playwright against a locally running Worker.

The Workers Testing Landscape

There are three approaches, each with different trade-offs:

  1. Miniflare (embedded) — runs Workers in Node.js using the workerd runtime. Full API compatibility, bindings work, no network required. Best for unit and integration tests.
  2. Wrangler dev (wrangler dev --local) — runs a full local preview with a hot-reloading HTTP server. Good for manual testing and e2e tests.
  3. Wrangler deploy + test — deploy to a preview environment, run tests against it. Highest fidelity, but slowest.

For most teams: Miniflare for unit/integration tests, Wrangler dev for e2e with Playwright.

Project Setup

A typical Workers project with Vitest and Miniflare:

npm create cloudflare@latest my-worker -- --type hello-world
cd my-worker
npm install --save-dev vitest @cloudflare/vitest-pool-workers

wrangler.toml:

name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[[kv_namespaces]]
binding = "CACHE"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
preview_id = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"

[[d1_databases]]
binding = "DB"
database_name = "my-db"
database_id = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"

[[r2_buckets]]
binding = "ASSETS"
bucket_name = "my-assets"

vitest.config.ts:

import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';

export default defineWorkersConfig({
  test: {
    poolOptions: {
      workers: {
        wrangler: { configPath: './wrangler.toml' },
      },
    },
  },
});

This configuration runs tests inside the actual workerd runtime — the same engine that runs on Cloudflare's edge. No Node.js compatibility shims needed.

Unit Testing Workers

Here's a simple routing Worker with authentication:

// src/index.ts
export interface Env {
  CACHE: KVNamespace;
  DB: D1Database;
  ASSETS: R2Bucket;
  API_SECRET: string;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === '/health') {
      return new Response(JSON.stringify({ status: 'ok' }), {
        headers: { 'Content-Type': 'application/json' },
      });
    }

    if (url.pathname.startsWith('/api/')) {
      const authHeader = request.headers.get('Authorization');
      if (authHeader !== `Bearer ${env.API_SECRET}`) {
        return new Response('Unauthorized', { status: 401 });
      }
      return handleApi(request, url, env);
    }

    return new Response('Not Found', { status: 404 });
  },
};

async function handleApi(request: Request, url: URL, env: Env): Promise<Response> {
  if (url.pathname === '/api/users' && request.method === 'GET') {
    const results = await env.DB.prepare('SELECT id, name, email FROM users').all();
    return new Response(JSON.stringify(results.results), {
      headers: { 'Content-Type': 'application/json' },
    });
  }

  return new Response('Not Found', { status: 404 });
}

Unit tests with @cloudflare/vitest-pool-workers:

// src/index.test.ts
import { env, SELF } from 'cloudflare:test';
import { describe, test, expect, beforeAll } from 'vitest';

describe('Worker routing', () => {
  test('GET /health returns 200', async () => {
    const response = await SELF.fetch('http://localhost/health');
    expect(response.status).toBe(200);
    const body = await response.json();
    expect(body.status).toBe('ok');
  });

  test('GET /api/users without auth returns 401', async () => {
    const response = await SELF.fetch('http://localhost/api/users');
    expect(response.status).toBe(401);
  });

  test('GET /api/users with valid auth returns 200', async () => {
    // env.API_SECRET is populated from wrangler.toml [vars] or test setup
    const response = await SELF.fetch('http://localhost/api/users', {
      headers: { Authorization: `Bearer ${env.API_SECRET}` },
    });
    expect(response.status).toBe(200);
  });

  test('unknown route returns 404', async () => {
    const response = await SELF.fetch('http://localhost/unknown');
    expect(response.status).toBe(404);
  });
});

SELF is the Worker itself, accessed through cloudflare:test. You call it like the Fetch API. The test runs inside the workerd runtime so the Request, Response, and URL objects are native — no polyfills.

Testing Workers KV

KV is eventually consistent, but in tests you get synchronous semantics. Test the full read-write-delete cycle:

// src/cache-handler.test.ts
import { env } from 'cloudflare:test';
import { describe, test, expect, beforeEach } from 'vitest';
import { handleCacheRequest } from './cache-handler';

describe('KV cache handler', () => {
  beforeEach(async () => {
    // Clean KV state between tests
    const keys = await env.CACHE.list();
    await Promise.all(keys.keys.map(k => env.CACHE.delete(k.name)));
  });

  test('stores value in KV', async () => {
    const request = new Request('http://localhost/cache/set', {
      method: 'POST',
      body: JSON.stringify({ key: 'user:123', value: { name: 'Alice' } }),
      headers: { 'Content-Type': 'application/json' },
    });

    const response = await handleCacheRequest(request, env);
    expect(response.status).toBe(200);

    // Verify directly in KV
    const stored = await env.CACHE.get('user:123', 'json');
    expect(stored).toEqual({ name: 'Alice' });
  });

  test('returns cached value', async () => {
    await env.CACHE.put('user:456', JSON.stringify({ name: 'Bob' }));

    const request = new Request('http://localhost/cache/get?key=user:456');
    const response = await handleCacheRequest(request, env);

    expect(response.status).toBe(200);
    const body = await response.json();
    expect(body.name).toBe('Bob');
  });

  test('returns 404 for missing key', async () => {
    const request = new Request('http://localhost/cache/get?key=nonexistent');
    const response = await handleCacheRequest(request, env);
    expect(response.status).toBe(404);
  });

  test('respects TTL expiration', async () => {
    // KV TTL in tests is simulated — put with 1-second expiration
    await env.CACHE.put('temp-key', 'temp-value', { expirationTtl: 1 });

    // Immediately available
    const immediate = await env.CACHE.get('temp-key');
    expect(immediate).toBe('temp-value');

    // Note: TTL expiry in Miniflare tests requires advancing fake timers
    // For expiry behavior, test with real Wrangler dev against real KV
  });
});

Testing D1 Databases

D1 is SQLite at the edge. Test database operations with schema migrations applied before tests run:

// vitest.config.ts (updated for D1)
import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';

export default defineWorkersConfig({
  test: {
    poolOptions: {
      workers: {
        wrangler: { configPath: './wrangler.toml' },
        miniflare: {
          d1Databases: { DB: 'test-db' },
        },
      },
    },
  },
});
// src/users.test.ts
import { env } from 'cloudflare:test';
import { describe, test, expect, beforeAll, beforeEach } from 'vitest';

beforeAll(async () => {
  // Apply schema
  await env.DB.exec(`
    CREATE TABLE IF NOT EXISTS users (
      id TEXT PRIMARY KEY,
      name TEXT NOT NULL,
      email TEXT UNIQUE NOT NULL,
      created_at INTEGER NOT NULL
    )
  `);
});

beforeEach(async () => {
  await env.DB.exec('DELETE FROM users');
});

describe('D1 user operations', () => {
  test('inserts and retrieves user', async () => {
    await env.DB.prepare(
      'INSERT INTO users (id, name, email, created_at) VALUES (?, ?, ?, ?)'
    ).bind('u1', 'Alice', 'alice@example.com', Date.now()).run();

    const result = await env.DB.prepare(
      'SELECT * FROM users WHERE id = ?'
    ).bind('u1').first();

    expect(result).not.toBeNull();
    expect(result!.name).toBe('Alice');
    expect(result!.email).toBe('alice@example.com');
  });

  test('enforces unique email constraint', async () => {
    await env.DB.prepare(
      'INSERT INTO users (id, name, email, created_at) VALUES (?, ?, ?, ?)'
    ).bind('u1', 'Alice', 'alice@example.com', Date.now()).run();

    await expect(
      env.DB.prepare(
        'INSERT INTO users (id, name, email, created_at) VALUES (?, ?, ?, ?)'
      ).bind('u2', 'Alice2', 'alice@example.com', Date.now()).run()
    ).rejects.toThrow();
  });

  test('lists all users', async () => {
    await env.DB.batch([
      env.DB.prepare('INSERT INTO users VALUES (?, ?, ?, ?)').bind('u1', 'Alice', 'a@test.com', 1),
      env.DB.prepare('INSERT INTO users VALUES (?, ?, ?, ?)').bind('u2', 'Bob', 'b@test.com', 2),
    ]);

    const results = await env.DB.prepare('SELECT * FROM users ORDER BY created_at').all();
    expect(results.results).toHaveLength(2);
    expect(results.results[0].name).toBe('Alice');
    expect(results.results[1].name).toBe('Bob');
  });
});

Testing R2 Object Storage

R2 tests follow the same pattern — access through env.ASSETS:

// src/storage.test.ts
import { env } from 'cloudflare:test';
import { describe, test, expect } from 'vitest';

describe('R2 storage', () => {
  test('uploads and retrieves object', async () => {
    const content = 'Hello, R2!';
    await env.ASSETS.put('test/hello.txt', content, {
      httpMetadata: { contentType: 'text/plain' },
    });

    const object = await env.ASSETS.get('test/hello.txt');
    expect(object).not.toBeNull();

    const text = await object!.text();
    expect(text).toBe(content);
    expect(object!.httpMetadata?.contentType).toBe('text/plain');
  });

  test('returns null for missing key', async () => {
    const object = await env.ASSETS.get('does/not/exist.txt');
    expect(object).toBeNull();
  });

  test('lists objects with prefix', async () => {
    await Promise.all([
      env.ASSETS.put('images/cat.jpg', 'cat data'),
      env.ASSETS.put('images/dog.jpg', 'dog data'),
      env.ASSETS.put('docs/readme.txt', 'readme data'),
    ]);

    const listed = await env.ASSETS.list({ prefix: 'images/' });
    expect(listed.objects).toHaveLength(2);
    expect(listed.objects.map(o => o.key)).toContain('images/cat.jpg');
  });
});

Testing Durable Objects

Durable Objects are stateful, single-instance coordinators. Test them through the Worker that creates and routes to them:

// src/counter.ts — Durable Object
export class Counter {
  private state: DurableObjectState;
  private value: number = 0;

  constructor(state: DurableObjectState) {
    this.state = state;
  }

  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === '/increment') {
      this.value = (await this.state.storage.get<number>('value') ?? 0) + 1;
      await this.state.storage.put('value', this.value);
      return new Response(JSON.stringify({ value: this.value }));
    }

    if (url.pathname === '/get') {
      const value = await this.state.storage.get<number>('value') ?? 0;
      return new Response(JSON.stringify({ value }));
    }

    return new Response('Not Found', { status: 404 });
  }
}
// src/counter.test.ts
import { SELF, env } from 'cloudflare:test';
import { describe, test, expect } from 'vitest';

describe('Counter Durable Object', () => {
  test('starts at zero', async () => {
    const id = env.COUNTER.newUniqueId();
    const stub = env.COUNTER.get(id);

    const response = await stub.fetch('http://do/get');
    const body = await response.json<{ value: number }>();
    expect(body.value).toBe(0);
  });

  test('increments correctly', async () => {
    const id = env.COUNTER.newUniqueId();
    const stub = env.COUNTER.get(id);

    await stub.fetch('http://do/increment');
    await stub.fetch('http://do/increment');
    const response = await stub.fetch('http://do/increment');

    const body = await response.json<{ value: number }>();
    expect(body.value).toBe(3);
  });

  test('different IDs are isolated', async () => {
    const id1 = env.COUNTER.newUniqueId();
    const id2 = env.COUNTER.newUniqueId();

    await env.COUNTER.get(id1).fetch('http://do/increment');
    await env.COUNTER.get(id1).fetch('http://do/increment');

    const response = await env.COUNTER.get(id2).fetch('http://do/get');
    const body = await response.json<{ value: number }>();
    expect(body.value).toBe(0);
  });
});

End-to-End Testing with Playwright

Start Wrangler's dev server and run Playwright against it:

# Terminal 1
wrangler dev --local --port 8787

# Terminal 2
npx playwright test
// e2e/worker.spec.ts
import { test, expect } from '@playwright/test';

const BASE_URL = 'http://localhost:8787';

test.describe('Worker e2e', () => {
  test('health check responds correctly', async ({ request }) => {
    const response = await request.get(`${BASE_URL}/health`);
    expect(response.ok()).toBeTruthy();
    const body = await response.json();
    expect(body.status).toBe('ok');
  });

  test('authenticated API call succeeds', async ({ request }) => {
    const response = await request.get(`${BASE_URL}/api/users`, {
      headers: { Authorization: 'Bearer test-secret' },
    });
    expect(response.ok()).toBeTruthy();
    const users = await response.json();
    expect(Array.isArray(users)).toBe(true);
  });

  test('full page renders correctly in browser', async ({ page }) => {
    await page.goto(`${BASE_URL}/`);
    await expect(page.locator('h1')).toBeVisible();
    await expect(page.locator('h1')).toContainText('Welcome');
  });
});

For CI, use the webServer option in playwright.config.ts to start Wrangler automatically:

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  webServer: {
    command: 'wrangler dev --local --port 8787',
    port: 8787,
    reuseExistingServer: !process.env.CI,
    stdout: 'pipe',
    stderr: 'pipe',
  },
  use: {
    baseURL: 'http://localhost:8787',
  },
});

Continuous Monitoring

Edge Workers are fast, but edge caching, KV replication lag, and Durable Object contention can cause subtle production issues that never appear in local tests. HelpMeTest monitors your deployed Workers endpoints continuously, running tests from multiple regions to catch latency regressions and behavioral differences across PoPs before users do.

Read more

Start now free