You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: guide/learn/setup-teardown.md
+33-35Lines changed: 33 additions & 35 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,20 +1,20 @@
1
1
---
2
-
title: Setup and Teardown | Guide
2
+
title: 初始化与清理 | 指南
3
3
prev:
4
-
text: Testing Asynchronous Code
4
+
text: 测试异步代码
5
5
link: /guide/learn/async
6
6
next:
7
-
text: Mock Functions
7
+
text: 模拟函数
8
8
link: /guide/learn/mock-functions
9
9
---
10
10
11
-
# Setup and Teardown
11
+
# 初始化与清理 {#setup-and-teardown}
12
12
13
-
Often while writing tests, you need to do some work before tests run (initialize data, connect to a database, start a server) and clean up afterwards. Rather than duplicating this code in every test, Vitest provides lifecycle hooks that run automatically at the right time.
The most common hooks are [`beforeEach`](/api/hooks#beforeeach)and[`afterEach`](/api/hooks#aftereach). As the names suggest, `beforeEach`runs before every test in the file, and `afterEach`runs after every test, even if the test fails. This makes them perfect for ensuring each test starts with a known state.
Without these hooks, the second test's `push`would affect any test that runs after it, which is a classic source of flaky tests. The hooks guarantee clean state for every test.
Some setup is too expensive to repeat for every test. If you need to connect to a database, start a server, or load a large file, doing that before every test would slow your suite down dramatically. That's what [`beforeAll`](/api/hooks#beforeall)and[`afterAll`](/api/hooks#afterall)are for. They run once for the entire file:
The database connection is created once, shared across all tests, and then closed when the file finishes running.
74
+
数据库连接只创建一次,在所有测试间共享,并在文件运行结束时关闭。
75
75
76
-
## Scoping with `describe`
76
+
## 使用 `describe` 进行作用域限定 {#scoping-with-describe}
77
77
78
-
Hooks defined inside a `describe`block only apply to the tests within that block. Top-level hooks apply to every test in the file. This lets you set up different state for different groups of tests:
Each`describe`block has its own `beforeEach`that only affects the tests inside it. The string tests don't know or care about the `value`variable, and vice versa.
When you have hooks at multiple levels, it's helpful to understand the order they run in. Top-level hooks wrap around inner hooks, forming a nesting structure:
118
+
当你在多个层级上设置钩子时,了解它们的执行顺序会很有用。顶层钩子包裹着内层钩子,形成一种嵌套结构:
119
119
120
120
```js
121
121
import { afterAll, afterEach, beforeAll, beforeEach, describe, test } from'vitest'
@@ -139,7 +139,7 @@ describe('suite', () => {
139
139
})
140
140
```
141
141
142
-
This produces the following output:
142
+
这会产生以下输出:
143
143
144
144
```
145
145
1 - beforeAll
@@ -156,11 +156,9 @@ This produces the following output:
156
156
8 - afterAll
157
157
```
158
158
159
-
Notice the pattern: `beforeAll`and`afterAll`run once for the entire suite, while `beforeEach`and`afterEach`repeat for every test. Within each test, outer `beforeEach`runs first (setting up the broadest context), then inner `beforeEach`runs (narrowing the context). After the test, the order reverses: inner `afterEach`cleans up the narrow context first, then outer `afterEach`handles the broader cleanup.
Sometimes you create a resource inside a test that needs to be cleaned up afterwards. You could use `afterEach`, but that means the cleanup is separated from the setup, which can make the test harder to follow. [`onTestFinished`](/api/hooks#ontestfinished) lets you register a cleanup function right where you create the resource:
A similar pattern works with `beforeEach`. You can return a cleanup function and Vitest will call it after each test. This is especially nice when the setup and teardown are closely related:
The examples above use `let`variables and `beforeEach`to set up shared state. This works, but it has some downsides: the variable declarations are separated from the initialization, the types require explicit annotation, and it's easy to forget to clean up.
Vitest offers a better pattern for this with [`test.extend`](/guide/test-context#extend-test-context). You define reusable **fixtures** that are automatically created for each test and cleaned up afterwards:
@@ -217,13 +215,13 @@ test('user is created', ({ db, user }) => {
217
215
})
218
216
```
219
217
220
-
Fixtures are only initialized when a test actually uses them (by destructuring them from the context), and they can depend on each other. This makes them a great alternative to `beforeEach`/`afterEach`for most setup and teardown patterns.
If you have setup code that should run before every test file in your project (things like polyfills, global configuration, or custom matchers), you can put it in a setup file and point to it with the [`setupFiles`](/config/setupfiles)config option:
Unlike`beforeAll`, which runs once per file, setup files run in a separate phase before the test file even starts being collected. This makes them the right place for things like extending the `expect` API or configuring global polyfills.
244
+
与每个文件运行一次的`beforeAll` 不同,初始化文件在测试文件甚至开始收集之前,在一个独立的阶段运行。这使得它们非常适合扩展 `expect` API 或配置全局 polyfills 等操作。
247
245
248
246
::: tip
249
-
For advanced cases where your test needs to run *inside* a wrapping context (like a database transaction or a tracing span), see the [`aroundEach`](/api/hooks#aroundeach)and[`aroundAll`](/api/hooks#aroundall)hooks. For the complete lifecycle picture, see [Test Run Lifecycle](/guide/lifecycle).
0 commit comments