Replies: 1 comment
-
I guess you have to use pre-release version of vitest-pool-workers lib to internally use miniflare to run the test and access to D1 test database. You can follow this step.
5 But If you want to mock D1 database for endpoint request. You have to create a mock env and pass env.D1 to the mock env. I'm using hono framework, I'm not sure how to implement it in plain cloudflare worker, so I write a sample code so you can get the idea. So just update the xxx.test.ts as below
I attached references I used Hope that's help. |
Beta Was this translation helpful? Give feedback.
-
Environment:
Wrangler - 3.5.1
Miniflare - 3.20230814.1
Vitest - 0.33.0
Vitest-environment-miniflare - 2.14.0
I created a D1 database and I can successfully access it in my cloudflare worker. I have this added in my "wrangler.toml" file:
Then in the worker code (worker.ts), I can run SQL queries by using "env.DB" (calling env.DB.prepare(), then run() on the resulting statement. It finds the tables I have in the database and can INSERT / SELECT to/from the tables.
I also have a vitest unit test that tests the worker. I can run the worker from it successfully. How do I access the database from this test?
My vitest.config.ts is as follows:
The way I am running the test is using this command from the terminal:
NODE_OPTIONS=--experimental-vm-modules npx vitest run
I have tried the following with no success:
const env = getMiniflareBindings();
or
const { __D1_BETA__DB } = getMiniflareBindings()
When I try to run a statement using env.__D1_BETA__DB or __D1_BETA__DB in the unit test, it cannot find the tables that I have in my database. What is the correct way to be able to access the database in the unit test?
Thanks.
Beta Was this translation helpful? Give feedback.
All reactions