Picture this: Your tests were working perfectly fine. Life was good. Then you innocently add ONE import from cloudflare:test to your setup file, and suddenly ALL YOUR MOCKS ARE LYING TO YOU. They exist, but they do nothing. They're like ghost mocks, haunting your codebase with their useless presence.
// The import that ruined everything
import { env, applyD1Migrations } from "cloudflare:test";- All your mocks suddenly decide to go on vacation
- Hours of your life wasted staring at perfectly valid mock code that just... doesn't... work
- That growing feeling of imposter syndrome as you question every life decision that led you to this moment
- Stack Overflow has no answers (the true mark of despair)
- Your console.log debugging is starting to look like a cry for help
After sacrificing several cups of coffee and what felt like years of your life, you stumble upon this innocent little note in the Vitest wiki:
Vitest will not mock modules that were imported inside a setup file because they are cached by the time a test file is running.
WHAT. DO. YOU. MEAN.
Apparently, that single cloudflare:test import in your setup file decided to invite all its module friends over for a caching party, and now they're all too drunk on memory to be mocked properly.
Add THREE LINES OF CODE to your setup file:
// test/setup/setup.ts
import { env, applyD1Migrations } from "cloudflare:test";
// Your setup code here
await applyD1Migrations(env.DB, env["TEST_MIGRATIONS"]);
// The magic incantation that fixes everything
vi.resetModules(); // <-- THIS. THIS IS ALL IT NEEDED.- Time lost: Several hours of your life you'll never get back
- Hair pulled: Approximately 47 strands
- Coffee consumed: [REDACTED] cups
- Times questioned career choice: 23
- Slack messages deleted before sending: 12 (they were not professional)
- Module caching is a silent killer
- The solution is always simpler than your 47 failed attempts to fix it
- When in doubt,
vi.resetModules() - Document everything because future you will thank past you for saving them from this particular circle of hell
- The Cloudflare Workers testing documentation is now your bedtime reading
If you're reading this because you're experiencing the same issue, congratulations! You've found the solution much faster than the poor soul who wrote this documentation. If you're reading this out of curiosity, consider yourself warned. And remember, somewhere out there, a developer spent hours of their life so you wouldn't have to.
Dedicated to all the developers who have ever yelled "BUT IT SHOULD WORK!" at their screens.