hono cloudflare 工作 - vitest 中的环境变量

问题描述 投票:0回答:1

使用 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);
      });
    });

更多详情:

  1. 测试开始时,我得到预期的输出:
    Using vars defined in .dev.vars
  2. 其他人建议违背文档并使用 .env 文件。
  3. 我尝试了
    vi.stubEnv
    但没有成功。
cloudflare-workers hono
1个回答
0
投票

答案可以在 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 文档中对此缺乏强调:

另一个例子是这里

© www.soinside.com 2019 - 2024. All rights reserved.