---
title: Testing
description: "Test Models and your Worker against a real D1 database with Vitest and Miniflare."
seo:
  description: "Test Active Record Models and your Cloudflare Worker against a real D1 database with Vitest and Miniflare, with your migrations applied to each test database."
---

## At a glance

| To                             | Write                                                        |
| ------------------------------ | ------------------------------------------------------------ |
| get a real D1 database in Node | Miniflare’s `getD1Database`, with your migrations applied    |
| run a Model’s code in a test   | `withDatabase(connect(database.binding), async () => { … })` |
| call your Worker in a test     | `withDatabase(…, () => worker.fetch(request))`               |
| query a database you hold      | `connect(database.binding).model(User)`                      |

## The Model

The tests below check this Model and Worker, with the users table its migration creates:

```ts user.ts
import { ApplicationRecord } from "./application-record";

export class User extends ApplicationRecord {
  static {
    this.beforeValidation((user) => {
      user.email = user.email.toLowerCase();
    });
  }
}
```

```ts index.ts
import { User } from "./models/user";

// The app's Worker: here, one route that lists the users' emails.
export default {
  async fetch() {
    return Response.json(await User.order({ email: "asc" }).pluck("email"));
  },
} satisfies ExportedHandler<Env>;
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: ae4437c2fc95

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** users — last changed by 0001_create_users.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    users: { attributes: users, primaryKey: "id" },
  },
  models: { User: "users" },
});

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
```

```sql D1
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL
);
```

```sql Postgres
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL
);
```

## Installing

[Miniflare](https://developers.cloudflare.com/workers/testing/miniflare/) runs Cloudflare’s runtime, D1 included, inside Node:

```sh
npm install --save-dev vitest miniflare@4
```

## Creating a test database

Start Miniflare with a D1 database, and apply a folder of migrations to it, in order:

```ts test/d1.ts
import { readdirSync, readFileSync } from "node:fs";
import { Miniflare } from "miniflare";

export async function testDatabase(folder = "migrations") {
  const mf = new Miniflare({ modules: true, script: "export default {}", d1Databases: ["DB"] });
  const binding = await mf.getD1Database("DB");
  for (const file of readdirSync(folder).sort()) {
    // Each migration's statements, without its comments, applied together.
    const statements = readFileSync(`${folder}/${file}`, "utf8")
      .replace(/^\s*--.*$/gm, "")
      .split(/;\s*$/m)
      .map((statement) => statement.trim())
      .filter(Boolean);
    if (statements.length > 0)
      await binding.batch(statements.map((statement) => binding.prepare(statement)));
  }
  return { binding, dispose: () => mf.dispose() };
}
```

## Testing Models

Outside a Worker there’s no binding, so run the test’s code inside `withDatabase`. This checks that `User` saves emails in lowercase:

```ts test/users.test.ts
import { withDatabase } from "@forestfuture/active-record";
import { connect } from "@forestfuture/active-record/d1";
import { afterAll, beforeAll, expect, test } from "vitest";
import { User } from "../src/models/user";
import { testDatabase } from "./d1";

let database: Awaited<ReturnType<typeof testDatabase>>;
beforeAll(async () => (database = await testDatabase()));
afterAll(() => database.dispose());

test("emails are saved in lowercase", async () => {
  await withDatabase(connect(database.binding), async () => {
    const user = await User.create({ email: "Jane@Example.com" });
    expect((await User.find(user.id)).email).toBe("jane@example.com");
  });
});
```

Outside a Worker, the database given to `withDatabase` serves every Model on its adapter, whatever binding its base class names. For code that takes a database explicitly, pass it one: `connect(database.binding).model(User)`.

## Testing your Worker

Call your Worker’s `fetch` handler inside `withDatabase` too, and its queries use the test’s database. This calls the Worker in `src/index.ts`:

```ts test/worker.test.ts
import { withDatabase } from "@forestfuture/active-record";
import { connect } from "@forestfuture/active-record/d1";
import { afterAll, beforeAll, expect, test } from "vitest";
import worker from "../src/index";
import { testDatabase } from "./d1";

let database: Awaited<ReturnType<typeof testDatabase>>;
beforeAll(async () => (database = await testDatabase()));
afterAll(() => database.dispose());

test("GET lists users", async () => {
  const response = await withDatabase(connect(database.binding), () =>
    worker.fetch(new Request("https://example.com/")),
  );
  expect(response.status).toBe(200);
});
```

Each test file gets its own database.

:::note
If your Worker uses [`withSession`](/read-your-own-writes), call `fetch` without `withDatabase`. Pass the test’s database as `env.DB` instead, and `withSession` opens it for the request.
:::

:::note
To run tests inside the Workers runtime itself, use Cloudflare’s [Vitest integration](https://developers.cloudflare.com/workers/testing/vitest-integration/).
:::
