skip to content

In the Workers Vitest plugin, how do you apply a D1 database's migrations before tests run, and why does it take two functions?

level: middleimportance: should knowfreq 22%

answer

  1. Node.js reads, workerd applies
  2. readD1Migrations() in the config
  3. a test-only binding carries them
  4. applyD1Migrations() in a setup file
  5. d1_migrations records what ran

basics

~20 s

readD1Migrations() runs in Node.js in the Vitest config to read the .sql files; pass the result in as a test-only binding, then call applyD1Migrations(env.DB, migrations) from cloudflare:test in a setup file, inside workerd, before each test file.

solid answer

~40 s

Tests run in `workerd`, which cannot read the project's `migrations` directory, while the Vitest config is evaluated in Node.js, which can. So the work is split. In the config, pass an async function to `cloudflareTest()` that calls `readD1Migrations(path)` from `@cloudflare/vitest-plugin`; it returns the migrations ordered by number, each split into individual SQL statements, and the function hands them to the runtime as a binding such as `miniflare.bindings.TEST_MIGRATIONS`. A file listed in `test.setupFiles` then calls `applyD1Migrations(env.DB, env.TEST_MIGRATIONS)` from `cloudflare:test`, which applies only the migrations not yet recorded in its `d1_migrations` table. Storage is isolated per test file, so each file starts with an empty database, and the setup file runs before each one.

code

javascript · 16 lines
javascript
import path from "node:path";
import { cloudflareTest, readD1Migrations } from "@cloudflare/vitest-plugin";
import { defineConfig } from "vitest/config";

export default defineConfig({
  plugins: [
    cloudflareTest(async () => {
      const migrations = await readD1Migrations(path.join(import.meta.dirname, "migrations"));
      return {
        wrangler: { configPath: "./wrangler.jsonc" },
        miniflare: { bindings: { TEST_MIGRATIONS: migrations } },
      };
    }),
  ],
  test: { setupFiles: ["./test/apply-migrations.js"] },
});

go deeper

for a junior

Recall the pairing: readD1Migrations() in the Vitest config, applyD1Migrations() from cloudflare:test in a setup file, with a test-only binding between them.

for a middle

Explain why the split exists, Node.js reading files and workerd applying them, and why a setup file runs the migrations once per test file under per-file storage isolation.

for a senior

Use the real migration files as the test schema so a broken migration fails CI, and diagnose 'no such table' errors from a missing setup file or a reset() that removed the tables.

for a principal

Make 'tests build the schema from the migrations folder' a team rule, and decide where reference data lives, in migrations or in test fixtures, before the two drift apart.

## Why one function cannot do it A **D1 database** is Cloudflare's serverless SQL database, and its schema evolves through numbered `.sql` **migration** files in a folder such as `migrations/`. The same files that `wrangler d1 migrations apply` runs against a real database should build the schema in tests, so the suite tests the schema production actually has. Two different processes are involved in a Workers Vitest run: - **The Vitest config** is evaluated in **Node.js**, which can read files from disk. - **Setup files and test files** run inside **`workerd`**, which has no access to the project's file system. Reading the migrations and applying them therefore happen in different places, and a binding carries the data across. The data that crosses is small and plain. Each migration becomes an object with a `name`, the file name such as `0001_create_visits.sql`, and `queries`, an array of individual SQL statements split out of the file. Plain JSON like this can travel as an ordinary binding value, which is why no special transport is needed between the two processes. ## Step by step 1. In `vitest.config`, pass an `async` function to `cloudflareTest()` instead of a plain object. 2. Inside it, call `readD1Migrations(path.join(import.meta.dirname, "migrations"))`, imported from `@cloudflare/vitest-plugin`. It returns an array of `{ name, queries }` objects, ordered by migration number, with each file split into individual SQL statements. 3. Return `miniflare: { bindings: { TEST_MIGRATIONS: migrations } }` next to `wrangler.configPath`. The array becomes a plain JSON binding that exists only in tests. 4. List a setup file in `test.setupFiles`, and in it call `await applyD1Migrations(env.DB, env.TEST_MIGRATIONS)` with `applyD1Migrations` from `cloudflare:test` and `env` from `cloudflare:workers`. Setup files run inside `workerd` before each test file, and storage is isolated per test file, so every file gets an empty database with the full schema applied. ## What applyD1Migrations does - It validates its arguments, throwing a `TypeError` when the first is not a D1 binding or the second is not an array of migrations. - It creates the migrations table if it does not exist, named `d1_migrations` unless a third argument names another table. - It applies, in order, only the migrations whose names are not yet recorded there, and records each one. - Calling it again is therefore cheap and safe: already-applied migrations are skipped. | Function | Runs in | Imported from | Job | |---|---|---|---| | `readD1Migrations()` | Node.js, while the config loads | `@cloudflare/vitest-plugin` | Read and split the `.sql` files | | `applyD1Migrations()` | `workerd`, in a setup file or test | `cloudflare:test` | Apply unapplied migrations to a D1 binding | ## Why this beats hand-written schema in tests Creating tables with ad hoc `CREATE TABLE` statements at the top of a test file works once and then drifts: the next migration adds a column, production gets it, and the tests keep passing against a stale schema. Applying the real migration files means a broken migration fails the suite before anyone runs it against a remote database, and a query written against a column that no migration created fails in CI rather than in production. ## Keeping tests and production in step - In the Wrangler file, a D1 binding's `migrations_dir` names the folder Wrangler applies, defaulting to `./migrations`. `readD1Migrations()` does not read that key; it reads the path it is given, so the path in the Vitest config must name the same folder. - `migrations_table` in the Wrangler file renames the tracking table, which defaults to `d1_migrations`. Passing the same name as the third argument of `applyD1Migrations()` keeps the local database shaped like the real one, which matters only if code or tests query that table. - The pipeline still applies migrations to the real database separately, with `wrangler d1 migrations apply <database> --remote`. The test suite proves the migrations run cleanly in order on an empty database; it does not apply anything remotely. - A migration that edits data rather than schema deserves a test that seeds rows in the old shape, applies the migrations, and asserts the new shape. ## Pitfalls - **Forgetting the setup file**: queries fail with a `D1_ERROR` reporting `no such table`. - **Applying migrations in `globalSetup`**: global setup runs once in Node.js, outside `workerd` and outside each file's isolated storage, so it cannot prepare the databases tests see. - **Calling `reset()` between tests**: it deletes all bound data, tables included, so later tests need the migrations applied again. - **Nested migration layouts**: `readD1Migrations()` also accepts an options object (`migrationsDir`, `migrationsPattern`) so it can discover files laid out like `0001_init/migration.sql`, the same way Wrangler does.

  • Why not apply the migrations once in a Vitest globalSetup file?
    Global setup runs once in Node.js, outside `workerd`, and has no access to the D1 binding the tests use. Each test file also gets its own isolated storage, so even a schema created elsewhere would not be in the database a file sees. A setup file runs inside `workerd` before every test file, which is exactly where the schema must be built.
  • How does a test add rows the schema needs, such as reference data?
    Either ship the reference rows as part of a migration, so production and tests share them, or seed them in a `beforeAll` or `beforeEach` with `env.DB.prepare(...).bind(...).run()` after the migrations have been applied. Seeding through migrations keeps one source of truth; seeding in tests keeps fixture data out of production.

  • applyD1Migrations() can read the migrations folder from inside a test.
  • applyD1Migrations() re-runs every migration each time it is called.
  • Migrations applied once in globalSetup are visible to every test file.
  • readD1Migrations() should be imported from cloudflare:test inside the test file.
  • Hand-written CREATE TABLE statements in tests are as good as the real migrations.