Appearance
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.
使用 vitest 池工作进程进行 Cloudflare 测试会在运行时提供一个 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 Bindings 测试应用:
¥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 代码库示例 从旧测试系统迁移
¥@cloudflare/vitest-pool-workers Github Repository examples
Migrate from old testing system