Skip to content
Our Sponsors
Open in Anthropic

title: 单元测试 - Elysia 教程 layout: false search: false authors: [] head: - - meta - property: 'og:title' content: 单元测试 - Elysia 教程

- - meta
  - name: 'description'
    content: Elysia 提供了 Elysia.fetch 函数来轻松测试您的应用程序。

- - meta
  - property: 'og:description'
    content: Elysia 提供了 Elysia.fetch 函数来轻松测试您的应用程序。

单元测试

Elysia 提供了 Elysia.fetch 函数来轻松测试您的应用程序。

Elysia.fetch 接受一个 Web 标准请求,并返回类似于 浏览器 fetch API 的响应。

typescript
import { Elysia } from 'elysia'

const app = new Elysia()
	.get('/', '你好世界')

app.fetch(new Request('http://localhost/'))
	.then((res) => res.text())
	.then(console.log)

这将像真实请求一样运行请求(非模拟)。

测试

这允许我们在不运行服务器的情况下轻松测试我们的应用程序。

typescript
import { describe, it, expect } from 'bun:test'

import { Elysia } from 'elysia'

describe('Elysia', () => {
	it('应该返回 Hello World', async () => {
		const app = new Elysia().get('/', 'Hello World')

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

		expect(text).toBe('Hello World')
	})
})
typescript
import { describe, it, expect } from 'vitest'

import { Elysia } from 'elysia'

describe('Elysia', () => {
	it('应该返回 Hello World', async () => {
		const app = new Elysia().get('/', 'Hello World')

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

		expect(text).toBe('Hello World')
	})
})
typescript
import { describe, it, test } from '@jest/globals'

import { Elysia } from 'elysia'

describe('Elysia', () => {
	test('应该返回 Hello World', async () => {
		const app = new Elysia().get('/', 'Hello World')

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

		expect(text).toBe('Hello World')
	})
})

参见 单元测试

作业

让我们点击预览中的 图标来查看请求是如何记录的。

Show answer
  • index.ts