Skip to content

Cloudflare 测试

🌐 Cloudflare Testing

你可以使用 @cloudflare/vitest-pool-workers 轻松实现 Cloudflare 测试,但需要预先进行一些配置,更多信息可以在 Cloudflare 测试文档 中找到。

🌐 You can implement the Cloudflare testing easily with @cloudflare/vitest-pool-workers for which some configuration has to be made priorly more on that can be found over in Cloudflare Docs about testing.

Cloudflare 使用 vitest pool workers 测试在运行时提供一个 cloudflare:test 模块,该模块会暴露在测试期间作为第二个参数传入的环境,更多信息请参见 Cloudflare 测试 API 部分

🌐 Cloudflare Testing with vitest pool workers provide a cloudflare:test module at runtime which exposes the env passed in as the second argument during testing more on it in the Cloudflare Test APIs section.

以下是一个配置示例:

🌐 Below is an example of the configuration one can make:

ts
import { defineWorkersProject } from '@cloudflare/vitest-pool-workers/config'

export default defineWorkersProject(() => {
  return {
    test: {
      globals: true,
      poolOptions: {
        workers: { wrangler: { configPath: './wrangler.toml' } },
      },
    },
  }
})
toml
compatibility_date = "2024-09-09"
compatibility_flags = [ "nodejs_compat" ]

[vars]
MY_VAR = "my variable"

假设应用如下所示:

🌐 Imagine the application like the following:

ts
// src/index.ts
import { Hono } from 'hono'

type Bindings = {
  MY_VAR: string
}

const app = new Hono<{ Bindings: Bindings }>()

app.get('/hello', (c) => {
  return c.json({ hello: 'world', var: c.env.MY_VAR })
})

export default app

你可以通过将从模块 cloudflare:test 导出的 env 传递给 app.request() 来测试使用 Cloudflare 绑定的应用:

🌐 You can test the application with Cloudflare Bindings by passing in the env exposed from the module cloudflare:test to app.request():

ts
// 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',
    })
  })
})

另请参阅

🌐 See Also

'@cloudflare/vitest-pool-workers' [Github 仓库示例](https://github.com/cloudflare/workers-sdk/tree/main/fixtures/vitest-pool-workers-examples)\ [迁移出旧测试系统](https://developers.cloudflare.com/workers/testing/vitest-integration/get-started/migrate-from-miniflare-2/)

Hono 中文网 - 粤ICP备13048890号