Skip to content

Commit da602a9

Browse files
docschina-bothi-ogawadammy001AriPerkkiofenghan34
authored
docs(en): merge docs-cn/sync-docs into docs-cn/dev @ 8331872 (#399)
* docs: replace old `--threads` flag references (#5099) Co-authored-by: Anjorin Damilare <[email protected]> * feat(reporters): support custom options (#5111) * feat(config): add `snapshotSerializers` option (#5092) * feat(vitest): add onTestFinished hook (#5128) * feat(browser): run test files in isolated iframes (#5036) * feat(vitest): add github actions reporter (#5093) * docs(cn): synchronize the latest content --------- Co-authored-by: Hiroshi Ogawa <[email protected]> Co-authored-by: Anjorin Damilare <[email protected]> Co-authored-by: Ari Perkkiö <[email protected]> Co-authored-by: Han <[email protected]> Co-authored-by: Vladimir <[email protected]> Co-authored-by: elonehoo <[email protected]>
1 parent 6f94085 commit da602a9

File tree

4 files changed

+197
-9
lines changed

4 files changed

+197
-9
lines changed

api/index.md

+97
Original file line numberDiff line numberDiff line change
@@ -906,6 +906,10 @@ afterEach(async () => {
906906

907907
在这里,`afterEach` 可确保在每次测试运行后清除测试数据。
908908

909+
::: tip
910+
Vitest 1.3.0 新增 [`onTestFinished`](##ontestfinished-1-3-0) hook。你可以在测试执行过程中调用,以便在测试运行结束后清理任何状态。
911+
:::
912+
909913
### beforeAll
910914

911915
- **类型:** `beforeAll(fn: () => Awaitable<void>, timeout?: number)`
@@ -959,3 +963,96 @@ afterAll(async () => {
959963
```
960964

961965
这里的 `afterAll` 确保在所有测试运行后调用 `stopMocking` 方法。
966+
967+
## Test Hooks
968+
969+
Vitest 提供了一些 hooks,你可以在测试执行期间调用这些钩子,以便在测试运行结束后清理状态。
970+
971+
::: warning
972+
如果在测试体之外调用这些 hooks ,则会出错。
973+
:::
974+
975+
### onTestFinished <Badge type="info">1.3.0+</Badge>
976+
977+
这个 hook 总是在测试运行结束后调用。它在 `afterEach` 之后被调用,因为它们会影响测试结果。它接收一个包含当前测试结果的 `TaskResult`
978+
979+
```ts
980+
import { onTestFinished, test } from 'vitest'
981+
982+
test('performs a query', () => {
983+
const db = connectDb()
984+
onTestFinished(() => db.close())
985+
db.query('SELECT * FROM users')
986+
})
987+
```
988+
989+
::: warning
990+
如果要并发运行测试,应该始终使用测试上下文中的 `onTestFinished` ,因为 Vitest 不会在全局 hook 中跟踪并发测试:
991+
992+
```ts
993+
import { test } from 'vitest'
994+
995+
test.concurrent('performs a query', (t) => {
996+
const db = connectDb()
997+
t.onTestFinished(() => db.close())
998+
db.query('SELECT * FROM users')
999+
})
1000+
```
1001+
:::
1002+
1003+
这个 hook 在创建可重复使用的逻辑时特别有用:
1004+
1005+
```ts
1006+
// 这可以是一个单独的文件
1007+
function getTestDb() {
1008+
const db = connectMockedDb()
1009+
onTestFinished(() => db.close())
1010+
return db
1011+
}
1012+
1013+
test('performs a user query', async () => {
1014+
const db = getTestDb()
1015+
expect(
1016+
await db.query('SELECT * from users').perform()
1017+
).toEqual([])
1018+
})
1019+
1020+
test('performs an organization query', async () => {
1021+
const db = getTestDb()
1022+
expect(
1023+
await db.query('SELECT * from organizations').perform()
1024+
).toEqual([])
1025+
})
1026+
```
1027+
1028+
### onTestFailed
1029+
1030+
只有在测试失败后才会调用这个 hook 。它在 `afterEach` 之后被调用,因为它们会影响测试结果。它将接收一个包含当前测试结果的 `TaskResult` 。这个 hook 对调试非常有用。
1031+
1032+
```ts
1033+
import { onTestFailed, test } from 'vitest'
1034+
1035+
test('performs a query', () => {
1036+
const db = connectDb()
1037+
onTestFailed((e) => {
1038+
console.log(e.result.errors)
1039+
})
1040+
db.query('SELECT * FROM users')
1041+
})
1042+
```
1043+
1044+
::: warning
1045+
如果要并发运行测试,应始终使用测试上下文中的 `onTestFailed` ,因为 Vitest 不会在全局 hook 中跟踪并发测试:
1046+
1047+
```ts
1048+
import { test } from 'vitest'
1049+
1050+
test.concurrent('performs a query', (t) => {
1051+
const db = connectDb()
1052+
onTestFailed((result) => {
1053+
console.log(result.errors)
1054+
})
1055+
db.query('SELECT * FROM users')
1056+
})
1057+
```
1058+
:::

config/index.md

+29-8
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ test("use jsdom in this test file", () => {
494494
});
495495
```
496496

497-
如果你使用 [`--threads=false`](#threads) 标志运行 Vitest,你的测试将按以下顺序运行`node`, `jsdom`, `happy-dom`, `edge-runtime`, `custom environments` 这意味着,具有相同环境的每个测试都组合在一起,但仍按顺序运行
497+
如果使用 [`--isolate=false`](#isolate-1-1-0) 运行 Vitest,测试将按以下顺序运行`node``jsdom``happy-dom``edge-runtime``custom environments`也就是说,具有相同环境的每个测试都会被分组,但仍会按顺序运行
498498

499499
从 0.23.0 开始,你还可以定义自定义环境。 当使用非内置环境时,Vitest 将尝试加载包 `vitest-environment-${name}`。 该包应导出一个具有 `Environment` 属性的对象:
500500

@@ -564,8 +564,8 @@ import { defineConfig } from "vitest/config";
564564
export default defineConfig({
565565
test: {
566566
poolMatchGlobs: [
567-
// all tests in "worker-specific" directory will run inside a worker as if you enabled `--threads` for them,
568-
["**/tests/worker-specific/**", "threads"],
567+
// all tests in "worker-specific" directory will run inside a worker as if you enabled `--pool=threads` for them,
568+
['**/tests/worker-specific/**', 'threads'],
569569
// run all tests in "browser" directory in an actual browser
570570
["**/tests/browser/**", "browser"],
571571
// all other tests will run based on "browser.enabled" and "threads" options, if you didn't specify other globs
@@ -666,7 +666,7 @@ try {
666666

667667
#### vmForks<NonProjectOption />
668668

669-
`vmThreads` 池类似,但通过 [tinypool](https://github.com/tinylibs/tinypool) 使用 `child_process` 而不是 `worker_threads`测试与主进程之间的通信速度不如 `vmThreads` 池快。与进程相关的 API(如 `process.chdir()` )在 `vmForks` 池中可用。请注意,该池与 `vmThreads` 中列出的池具有相同的缺陷。
669+
`vmThreads` 池类似,但通过 [tinypool](https://github.com/tinylibs/tinypool) 使用 `child_process` 而不使用 `worker_threads`测试与主进程之间的通信速度虽然不如 `vmThreads` 快。但进程相关的 API(如 `process.chdir()` )在 `vmForks` 中却可以使用。请注意,这个与 `vmThreads` 中列出的池具有相同的缺陷。
670670

671671
### poolOptions<NonProjectOption /> <Badge type="info">1.0.0+</Badge>
672672

@@ -1005,8 +1005,8 @@ setup 文件的路径。它们将运行在每个测试文件之前。
10051005

10061006
你可以在全局设置文件中使用 `process.env.VITEST_POOL_ID`(类似整数的字符串)来区分不同的线程。
10071007

1008-
:::tip 提醒
1009-
请注意,如果你正在运行 [`--threads=false`](#threads),则此设置文件将在同一全局范围内多次运行。 这意味着,你在每次测试之前都在访问同一个全局对象,因此请确保你做的事情没有超出你的需要
1008+
:::tip
1009+
请注意,如果运行 [`--isolate=false`](#isolate-1-1-0) ,这个-设置文件将在全局范围内多次运行。这意味着每次测试前都要访问同一个全局对象,因此请确保不要重复做同一件事
10101010
:::
10111011

10121012
比如,你可能依赖于一个全局变量:
@@ -1550,7 +1550,21 @@ test("doNotRun", () => {
15501550
- **默认值:** `true`
15511551
- **命令行终端:** `--browser.isolate`, `--browser.isolate=false`
15521552

1553-
在每个测试之后隔离测试环境。
1553+
在单独的 iframe 中运行每个测试。
1554+
1555+
### browser.fileParallelism <Badge type="info">1.3.0+</Badge>
1556+
1557+
- **类型:** `boolean`
1558+
- **默认值:**[`fileParallelism`](#fileparallelism-110)相同
1559+
- **命令行终端:** `--browser.fileParallelism=false`
1560+
1561+
同时创建所有测试 iframe,使它们并行运行。
1562+
1563+
这样就无法使用交互式 API(如点击或悬停),因为屏幕上会同时出现多个 iframe,但如果你的测试不依赖于这些 API,那么同时运行所有 iframe 可能会快很多。
1564+
1565+
::: tip
1566+
如果通过 [`browser.isolate=false`](#browserisolate) 禁用了隔离,由于测试运行器的特性,测试文件仍会一个接一个地运行。
1567+
:::
15541568

15551569
#### browser.api
15561570

@@ -1712,9 +1726,16 @@ export default defineConfig({
17121726
::: tip
17131727
请注意,此对象上的 `plugins` 字段将被忽略。
17141728

1715-
如果需要通过 pretty-format 插件扩展快照序列化器,请使用 [`expect.addSnapshotSerializer`](/api/expect#expect-addsnapshotserializer) API
1729+
如果你需要通过 pretty-format 插件扩展快照序列器,请使用 [`expect.addSnapshotSerializer`](/api/expect#expect-addsnapshotserializer) [snapshotSerializers](#snapshotserializers-1-3-0) 选项
17161730
:::
17171731

1732+
### snapshotSerializers<NonProjectOption /> <Badge type="info">1.3.0+</Badge>
1733+
1734+
- **Type:** `string[]`
1735+
- **Default:** `[]`
1736+
1737+
A list of paths to snapshot serializer modules for snapshot testing, useful if you want add custom snapshot serializers. See [Custom Serializer](/guide/snapshot#custom-serializer) for more information.
1738+
17181739
### resolveSnapshotPath<NonProjectOption />
17191740

17201741
- **类型**: `(testPath: string, snapExtension: string) => string`

guide/reporters.md

+37
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,23 @@ export default defineConfig({
2626
})
2727
```
2828

29+
某些报告器可以通过传递附加选项进行自定义。具体选项将在下面的章节中介绍。
30+
31+
:::tip
32+
从 Vitest v1.3.0 开始支持
33+
:::
34+
35+
```ts
36+
export default defineConfig({
37+
test: {
38+
reporters: [
39+
'default',
40+
['junit', { suiteName: 'UI tests' }]
41+
],
42+
},
43+
})
44+
```
45+
2946
## 报告器输出
3047

3148
默认情况下,Vitest 的报告器会将输出打印到终端。当使用 `json``html``junit` 报告器时,你可以在 Vite 配置文件中或通过 CLI 加入 `outputFile` [配置选项](https://vitest.dev/config/#outputfile),将测试输出写入文件。
@@ -248,6 +265,17 @@ AssertionError: expected 5 to be 4 // Object.is equality
248265
</testsuite>
249266
</testsuites>
250267
```
268+
输出的 XML 包含嵌套的 `testsuites``testcase` 标记。你可以使用环境变量 `VITEST_JUNIT_SUITE_NAME``VITEST_JUNIT_CLASSNAME` 分别配置它们的 `name``classname` 属性。这些属性也可通过 reporter 选项进行自定义:
269+
270+
```ts
271+
export default defineConfig({
272+
test: {
273+
reporters: [
274+
['junit', { suiteName: 'custom suite name', classname: 'custom-classname' }]
275+
]
276+
},
277+
})
278+
```
251279

252280
输出的 XML 包含嵌套的 `testsuites``testcase` 标记。你可以使用环境变量 `VITEST_JUNIT_SUITE_NAME``VITEST_JUNIT_CLASSNAME` 分别配置它们的名称和类名属性。
253281

@@ -437,6 +465,15 @@ export default defineConfig({
437465

438466
:::
439467

468+
### Github Actions Reporter <Badge type="info">1.3.0+</Badge>
469+
470+
输出[工作流命令](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message)为测试失败提供注释。当 `process.env.GITHUB_ACTIONS === 'true'` 时,该报告器会自动启用,因此无需任何配置。
471+
472+
<img alt="Github Actions" img-dark src="https://github.com/vitest-dev/vitest/assets/4232207/336cddc2-df6b-4b8a-8e72-4d00010e37f5">
473+
<img alt="Github Actions" img-light src="https://github.com/vitest-dev/vitest/assets/4232207/ce8447c1-0eab-4fe1-abef-d0d322290dca">
474+
475+
476+
440477
## 自定义报告器
441478

442479
你可以使用从 NPM 安装的第三方自定义报告器,方法是在 `reporter` 选项中指定它们的软件包名称:

guide/snapshot.md

+34-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ test('image snapshot', () => {
116116

117117
你可以添加自己的逻辑来修改快照的序列化方式。像 Jest 一样,Vitest 为内置的 JavaScript 类型、HTML 元素、ImmutableJS 和 React 元素提供了默认的序列化程序。
118118

119-
序列化模块示例:
119+
可以使用 [`expect.addSnapshotSerializer`](/api/expect#expect-addsnapshotserializer) 添加自定义序列器。
120120

121121
```ts
122122
expect.addSnapshotSerializer({
@@ -136,6 +136,39 @@ expect.addSnapshotSerializer({
136136
})
137137
```
138138

139+
我们还支持 [snapshotSerializers](/config/#snapshotserializers-1-3-0) 选项来隐式添加自定义序列化器。
140+
141+
```ts
142+
import { SnapshotSerializer } from 'vitest'
143+
144+
export default {
145+
serialize(val, config, indentation, depth, refs, printer) {
146+
// `printer` 是一个使用现有插件序列化数值的函数。
147+
return `Pretty foo: ${printer(
148+
val.foo,
149+
config,
150+
indentation,
151+
depth,
152+
refs,
153+
)}`
154+
},
155+
test(val) {
156+
return val && Object.prototype.hasOwnProperty.call(val, 'foo')
157+
},
158+
} satisfies SnapshotSerializer
159+
```
160+
161+
162+
```ts
163+
import { defineConfig } from 'vite'
164+
165+
export default defineConfig({
166+
test: {
167+
snapshotSerializers: ['path/to/custom-serializer.ts']
168+
},
169+
})
170+
```
171+
139172
如下所示的测试添加后:
140173

141174
```ts

0 commit comments

Comments
 (0)