使用 Hono 创建 Cloudflare Worker,使用 vitest 时如何读取环境变量? 下面的代码适用于
wrangler dev
但当我使用 vitest 时失败:
[GET] http://localhost:8787/blackholesun
--> GET /blackholesun 500 3ms
TypeError: Cannot read properties of undefined (reading 'FOOBAR')
import { Hono } from "hono";
type Bindings = {
SECURITY_HEADER_NAME: string;
SECRET_KEY: string;
FOOBAR: string;
};
const app = new Hono<{ Bindings: Bindings }>();
app.notFound((c) => {
console.log("[!] foobar: ", c.env.FOOBAR);
return c.text("page not found", 404);
});
单元测试:
describe("test basic routes", () => {
....
it("check 404 returned ok", async () => {
const blackholeReq = new Request("http://localhost:8787/blackhole", {
method: "GET"
});
const res = await app.request(blackholeReq);
expect(res.status).toBe(404);
});
});
更多详情:
Using vars defined in .dev.vars
。vi.stubEnv
但没有成功。答案可以在 Hono 的一篇关于 vitest 和 Cloudflare 工作人员的新文章这里找到。 我错过了
import { env } from 'cloudflare:test'
。
// src/index.test.ts
import { env } from 'cloudflare:test'
import app from './index'
describe('Example', () => {
it('Should return 200 response', async () => {
const res = await app.request('/hello', {}, env)
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
hello: 'world',
var: 'my variable',
})
})
})
好吧,我的问题是 Cloudflare 文档中对此缺乏强调:
另一个例子是这里。