Skip to content

单元测试

¥Unit Test

由于符合 WinterCG 标准,我们可以使用请求/响应类来测试 Elysia 服务器。

¥Being WinterCG compliant, we can use Request / Response classes to test an Elysia server.

Elysia 提供了 Elysia.handle 方法,该方法接受 Web 标准 请求 并返回 响应,模拟 HTTP 请求。

¥Elysia provides the Elysia.handle method, which accepts a Web Standard Request and returns Response, simulating an HTTP Request.

Bun 包含一个内置的 测试运行者,它通过 bun:test 模块提供类似 Jest 的 API,从而方便创建单元测试。

¥Bun includes a built-in test runner that offers a Jest-like API through the bun:test module, facilitating the creation of unit tests.

在项目根目录下创建 test/index.test.ts 文件,并包含以下内容:

¥Create test/index.test.ts in the root of project directory with the following:

typescript
// test/index.test.ts
import { describe, expect, it } from 'bun:test'
import { Elysia } from 'elysia'

describe('Elysia', () => {
    it('returns a response', async () => {
        const app = new Elysia().get('/', () => 'hi')

        const response = await app
            .handle(new Request('http://localhost/'))
            .then((res) => res.text())

        expect(response).toBe('hi')
    })
})

然后我们可以通过运行 bun test 进行测试。

¥Then we can perform tests by running bun test

bash
bun test

对 Elysia 服务器的新请求必须是完全有效的 URL,而不是 URL 的一部分。

¥New requests to an Elysia server must be a fully valid URL, NOT a part of a URL.

请求必须提供以下 URL:

¥The request must provide URL as the following:

URL有效
http://localhost/user
/user

我们还可以使用其他测试库(例如 Jest)来创建 Elysia 单元测试。

¥We can also use other testing libraries like Jest to create Elysia unit tests.

Eden 条约测试

¥Eden Treaty test

我们可以使用 Eden Treaty 为 Elysia 服务器创建端到端类型安全测试,如下所示:

¥We may use Eden Treaty to create an end-to-end type safety test for Elysia server as follows:

typescript
// test/index.test.ts
import { 
describe
,
expect
,
it
} from 'bun:test'
import {
Elysia
} from 'elysia'
import {
treaty
} from '@elysiajs/eden'
const
app
= new
Elysia
().
get
('/hello', 'hi')
const
api
=
treaty
(
app
)
describe
('Elysia', () => {
it
('returns a response', async () => {
const {
data
,
error
} = await
api
.
hello
.
get
()
expect
(
data
).
toBe
('hi')
}) })

有关设置和更多信息,请参阅 Eden 条约单元测试

¥See Eden Treaty Unit Test for setup and more information.