Skip to content

Commit de080a1

Browse files
Jinjiangeddyerburgh
authored andcommitted
docs(zh-cn): synced recent updates 195449e...42208d9 (vuejs#332)
* [docs][zh-cn] synced recent updates 195449e...42208d9 * [docs][zh-cn] translated testing-async-components
1 parent d1a79a9 commit de080a1

File tree

9 files changed

+172
-22
lines changed

9 files changed

+172
-22
lines changed

docs/en/guides/testing-async-components.md

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
# Testing Asynchronous Behavior
1+
# 测试异步行为
22

3-
To simplify testing, `vue-test-utils` applies DOM updates _synchronously_. However, there are some techniques you need to be aware of when testing a component with asynchronous behavior such as callbacks or promises.
3+
为了让测试变得简单,`vue-test-utils` _同步_应用 DOM 更新。不过当测试一个带有回调或 Promise 等异步行为的组件时,你需要留意一些技巧。
44

5-
One of the most common asynchronous behaviors is API calls and Vuex actions. The following examples shows how to test a method that makes an API call. This example uses Jest to run the test and to mock the HTTP library `axios`. More about Jest manual mocks can be found [here](https://facebook.github.io/jest/docs/en/manual-mocks.html#content).
5+
API 调用和 Vuex action 都是最常见的异步行为之一。下列例子展示了如何测试一个会调用到 API 的方法。这个例子使用 Jest 运行测试用例同时模拟了 HTTP `axios`。更多关于 Jest 的手动模拟的介绍可移步[这里](https://facebook.github.io/jest/docs/en/manual-mocks.html#content)
66

7-
The implementation of the `axios` mock looks like this:
7+
`axios` 的模拟实现大概是这个样子的:
88

99
``` js
1010
export default {
@@ -14,7 +14,7 @@ export default {
1414
}
1515
```
1616

17-
The below component makes an API call when a button is clicked, then assigns the response to `value`.
17+
下面的组件在按钮被点击的时候会调用一个 API,然后将响应的值赋给 `value`
1818

1919
``` html
2020
<template>
@@ -41,7 +41,7 @@ The below component makes an API call when a button is clicked, then assigns the
4141
</script>
4242
```
4343

44-
A test can be written like this:
44+
测试用例可以写成像这样:
4545

4646
``` js
4747
import { shallow } from 'vue-test-utils'
@@ -57,7 +57,7 @@ test('Foo', () => {
5757
})
5858
```
5959

60-
This test currently fails because the assertion is called before the promise in `fetchResults` resolves. Most unit test libraries provide a callback to let the runner know when the test is complete. Jest and Mocha both use `done`. We can use `done` in combination with `$nextTick` or `setTimeout` to ensure any promises resolve before the assertion is made.
60+
现在这则测试用例会失败,因为断言在 `fetchResults` 中的 Promise 完成之前就被调用了。大多数单元测试库都提供一个回调来使得运行期知道测试用例的完成时机。Jest Mocha 都是用了 `done`。我们可以和 `$nectTick``setTimeout` 结合使用 `done` 来确保任何 Promise 都会在断言之前完成。
6161

6262
``` js
6363
test('Foo', () => {
@@ -72,9 +72,9 @@ test('Foo', () => {
7272
})
7373
```
7474

75-
The reason `$nextTick` or `setTimeout` allow the test to pass is because the microtask queue where promise callbacks are processed run before the task queue, where `$nextTick` and `setTimeout` are processed. This means by the time the `$nexTick` and `setTimeout` run, any promise callbacks on the microtask queue will have been executed. See [here](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/) for a more detailed explanation.
75+
`$nextTick` `setTimeout` 允许测试通过的原因是 Promise 回调的 microtask 队列会在处理 `$nextTick` `setTimeout` 的任务队列之前先被处理。也就是说在 `$nextTick` `setTimeout` 运行的时候,任何 microtask 队列上的 Promise 回调都已经执行过了。更多的解释请移步[这里](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/)
7676

77-
Another solution is to use an `async` function and the npm package `flush-promises`. `flush-promises` flushes all pending resolved promise handlers. You can `await` the call of `flushPromises` to flush pending promises and improve the readability of your test.
77+
另一个解决方案时使用一个 `async` 函数配合 npm `flush-promises``flush-promises` 会清除所有等待完成的 Promise 具柄。你可以 `await` `flushPromiese` 调用,以此清除等待中的 Promise 并改进你的测试用例的可读性。
7878

7979
The updated test looks like this:
8080

@@ -94,5 +94,4 @@ test('Foo', () => {
9494
})
9595
```
9696

97-
This same technique can be applied to Vuex actions, which return a promise by default.
98-
97+
相同的技巧可以被运用在同样默认返回一个 Promise 的 Vuex action 中。

docs/zh-cn/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
* [选择一个测试运行器](guides/choosing-a-test-runner.md)
1010
* [用 Jest 测试单文件组件](guides/testing-SFCs-with-jest.md)
1111
* [用 Mocha 和 webpack 测试单文件组件](guides/testing-SFCs-with-mocha-webpack.md)
12+
* [测试异步行为](guides/testing-async-components.md)
1213
* [配合 Vue Router 使用](guides/using-with-vue-router.md)
1314
* [配合 Vuex 实用](guides/using-with-vuex.md)
1415
* [API](api/README.md)

docs/zh-cn/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
* [选择一个测试运行器](guides/choosing-a-test-runner.md)
88
* [用 Jest 测试单文件组件](guides/testing-SFCs-with-jest.md)
99
* [用 Mocha 和 webpack 测试单文件组件](guides/testing-SFCs-with-mocha-webpack.md)
10+
* [测试异步行为](guides/testing-async-components.md)
1011
* [配合 Vue Router 使用](guides/using-with-vue-router.md)
1112
 * [配合 Vuex 使用](guides/using-with-vuex.md)
1213
* [API](api/README.md)

docs/zh-cn/api/selectors.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@
2323

2424
Vue 组件也是有效的选择器。
2525

26-
`vue-test-utils` 使用 `name` 属性搜索匹配 Vue 组件的实例树。
27-
2826
```js
2927
// Foo.vue
3028

@@ -44,6 +42,16 @@ expect(wrapper.is(Foo)).toBe(true)
4442

4543
## 查找选项对象
4644

45+
### Name
46+
47+
`vue-test-utils` 允许通过一个查找选项对象在组件包裹器上根据 `name` 选择元素。
48+
49+
50+
```js
51+
const buttonWrapper = wrapper.find({ name: 'my-button' })
52+
buttonWrapper.trigger('click')
53+
```
54+
4755
### Ref
4856

4957
`vue-test-utils` 允许通过一个查找选项对象在组件包裹器上根据 `$ref` 选择元素。

docs/zh-cn/guides/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@
66
* [选择一个测试运行器](./choosing-a-test-runner.md)
77
* [用 Jest 测试单文件组件](./testing-SFCs-with-jest.md)
88
* [用 Mocha 和 webpack 测试单文件组件](./testing-SFCs-with-mocha-webpack.md)
9+
* [测试异步行为](./testing-async-components.md)
910
* [配合 Vue Router 使用](./using-with-vue-router.md)
1011
* [配合 Vuex 实用](./using-with-vuex.md)

docs/zh-cn/guides/testing-SFCs-with-jest.md

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ npm install --save-dev babel-jest
123123
}
124124
```
125125

126-
### 测试快照
126+
## 测试快照
127127

128128
你可以使用 [`vue-server-renderer`](https://github.com/vuejs/vue/tree/dev/packages/vue-server-renderer) 将组件渲染为一个字符串,这样它就可以为 [Jest 快照测试](https://facebook.github.io/jest/docs/en/snapshot-testing.html) 保存一个快照。
129129

@@ -148,13 +148,46 @@ npm install --save-dev jest-serializer-vue
148148
}
149149
```
150150

151-
### 放置测试文件
151+
## 放置测试文件
152152

153153
默认情况下,Jest 将会递归的找到整个工程里所有 `.spec.js``.test.js` 扩展名的文件。如果这不符合你的需求,你也可以在 `package.json` 里的配置段落中[改变它的 `testRegex`](https://facebook.github.io/jest/docs/en/configuration.html#testregex-string)
154154

155155
Jest 推荐你在被测试代码的所在目录下创建一个 `__tests__` 目录,但你也可以为你的测试文件随意设计自己习惯的文件结构。不过要当心 Jest 会为快照测试在临近测试文件的地方创建一个 `__snapshots__` 目录。
156156

157-
### 测试规范示例
157+
## 测试覆盖率
158+
159+
Jest 可以被用来生成多种格式的测试覆盖率报告。以下是一个简单的起步的例子:
160+
161+
扩展你的 `jest` 配置 (通常在 `package.json``jest.config.js` 中) 的 [`collectCoverage`](https://facebook.github.io/jest/docs/en/configuration.html#collectcoverage-boolean) 选项,然后添加 [`collectCoverageFrom`](https://facebook.github.io/jest/docs/en/configuration.html#collectcoveragefrom-array) 数组来定义需要收集测试覆盖率信息的文件。你还需要设置 [`mapCoverage`](https://facebook.github.io/jest/docs/en/configuration.html#mapcoverage-boolean)`true`,以确保测试覆盖率数据的精准。
162+
163+
```json
164+
{
165+
"jest": {
166+
// ...
167+
"collectCoverage": true,
168+
"collectCoverageFrom": [
169+
"**/*.{js,vue}",
170+
"!**/node_modules/**"
171+
],
172+
"mapCoverage": true
173+
}
174+
}
175+
```
176+
177+
这样就会开启[默认格式的测试覆盖率报告](https://facebook.github.io/jest/docs/en/configuration.html#coveragereporters-array-string)。你可以通过 `coverageReporters` 选项来定制它们。
178+
179+
```json
180+
{
181+
"jest": {
182+
// ...
183+
"coverageReporters": ["html", "text-summary"]
184+
}
185+
}
186+
```
187+
188+
更多文档内容请移步至 [Jest 配置文档](https://facebook.github.io/jest/docs/en/configuration.html#collectcoverage-boolean),在那里你可以找到覆盖率阀值、目标输出目录等选项。
189+
190+
## 测试规范示例
158191

159192
如果你已经熟悉了 Jasmine,你应该很适应 Jest 的[断言 API](https://facebook.github.io/jest/docs/en/expect.html#content)
160193

@@ -170,7 +203,7 @@ describe('Component', () => {
170203
})
171204
```
172205

173-
### 相关资料
206+
## 相关资料
174207

175208
- [该设置的示例工程](https://github.com/vuejs/vue-test-utils-jest-example)
176209
- [Vue Conf 2017 中的示例和幻灯片](https://github.com/codebryo/vue-testing-with-jest-conf17)

docs/zh-cn/guides/testing-SFCs-with-mocha-webpack.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,10 @@ npm run unit
170170

171171
喔,我们的测试运行起来了!
172172

173+
### 测试覆盖率
174+
175+
如果想设置 `mocha-webpack` 的测试覆盖率,请参照 [`mocha-webpack` 测试覆盖率指南](https://github.com/zinserjan/mocha-webpack/blob/master/docs/guides/code-coverage.md)
176+
173177
### 相关资料
174178

175179
- [该设置的示例工程](https://github.com/vuejs/vue-test-utils-mocha-webpack-example)
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# Testing Asynchronous Behavior
2+
3+
To simplify testing, `vue-test-utils` applies DOM updates _synchronously_. However, there are some techniques you need to be aware of when testing a component with asynchronous behavior such as callbacks or promises.
4+
5+
One of the most common asynchronous behaviors is API calls and Vuex actions. The following examples shows how to test a method that makes an API call. This example uses Jest to run the test and to mock the HTTP library `axios`. More about Jest manual mocks can be found [here](https://facebook.github.io/jest/docs/en/manual-mocks.html#content).
6+
7+
The implementation of the `axios` mock looks like this:
8+
9+
``` js
10+
export default {
11+
get: () => new Promise(resolve => {
12+
resolve({ data: 'value' })
13+
})
14+
}
15+
```
16+
17+
The below component makes an API call when a button is clicked, then assigns the response to `value`.
18+
19+
``` html
20+
<template>
21+
<button @click="fetchResults" />
22+
</template>
23+
24+
<script>
25+
import axios from 'axios'
26+
27+
export default {
28+
data () {
29+
return {
30+
value: null
31+
}
32+
},
33+
34+
methods: {
35+
async fetchResults () {
36+
const response = await axios.get('mock/service')
37+
this.value = response.data
38+
}
39+
}
40+
}
41+
</script>
42+
```
43+
44+
A test can be written like this:
45+
46+
``` js
47+
import { shallow } from 'vue-test-utils'
48+
import Foo from './Foo'
49+
jest.mock('axios')
50+
51+
test('Foo', () => {
52+
it('fetches async when a button is clicked', () => {
53+
const wrapper = shallow(Foo)
54+
wrapper.find('button').trigger('click')
55+
expect(wrapper.vm.value).toEqual('value')
56+
})
57+
})
58+
```
59+
60+
This test currently fails because the assertion is called before the promise in `fetchResults` resolves. Most unit test libraries provide a callback to let the runner know when the test is complete. Jest and Mocha both use `done`. We can use `done` in combination with `$nextTick` or `setTimeout` to ensure any promises resolve before the assertion is made.
61+
62+
``` js
63+
test('Foo', () => {
64+
it('fetches async when a button is clicked', (done) => {
65+
const wrapper = shallow(Foo)
66+
wrapper.find('button').trigger('click')
67+
wrapper.vm.$nextTick(() => {
68+
expect(wrapper.vm.value).toEqual('value')
69+
done()
70+
})
71+
})
72+
})
73+
```
74+
75+
The reason `$nextTick` or `setTimeout` allow the test to pass is because the microtask queue where promise callbacks are processed run before the task queue, where `$nextTick` and `setTimeout` are processed. This means by the time the `$nexTick` and `setTimeout` run, any promise callbacks on the microtask queue will have been executed. See [here](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/) for a more detailed explanation.
76+
77+
Another solution is to use an `async` function and the npm package `flush-promises`. `flush-promises` flushes all pending resolved promise handlers. You can `await` the call of `flushPromises` to flush pending promises and improve the readability of your test.
78+
79+
The updated test looks like this:
80+
81+
``` js
82+
import { shallow } from 'vue-test-utils'
83+
import flushPromises from 'flush-promises'
84+
import Foo from './Foo'
85+
jest.mock('axios')
86+
87+
test('Foo', () => {
88+
it('fetches async when a button is clicked', async () => {
89+
const wrapper = shallow(Foo)
90+
wrapper.find('button').trigger('click')
91+
await flushPromises()
92+
expect(wrapper.vm.value).toEqual('value')
93+
})
94+
})
95+
```
96+
97+
This same technique can be applied to Vuex actions, which return a promise by default.

docs/zh-cn/guides/using-with-vue-router.md

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77
为了避免这样的事情发生,我们创建了一个 `localVue` 并对其安装 Vue Router。
88

99
```js
10+
import { shallow, createLocalVue } from 'vue-test-utils'
1011
import VueRouter from 'vue-router'
11-
const localVue = createLocalVue()
1212

13+
const localVue = createLocalVue()
1314
localVue.use(VueRouter)
1415

1516
shallow(Component, {
@@ -21,11 +22,13 @@ shallow(Component, {
2122

2223
当你安装 Vue Router 的时候,`router-link``router-view` 组件就被注册了。这意味着我们无需再导入可以在应用的任意地方使用它们。
2324

24-
当我们运行测试的时候,需要令 vue-router 相关组件在我们挂载的组件中可用。有以下两种做法:
25+
当我们运行测试的时候,需要令 Vue Router 相关组件在我们挂载的组件中可用。有以下两种做法:
2526

2627
### 使用存根
2728

2829
```js
30+
import { shallow } from 'vue-test-utils'
31+
2932
shallow(Component, {
3033
stubs: ['router-link', 'router-view']
3134
})
@@ -34,9 +37,10 @@ shallow(Component, {
3437
### 为 localVue 安装 Vue Router
3538

3639
```js
40+
import { shallow, createLocalVue } from 'vue-test-utils'
3741
import VueRouter from 'vue-router'
38-
const localVue = createLocalVue()
3942

43+
const localVue = createLocalVue()
4044
localVue.use(VueRouter)
4145

4246
shallow(Component, {
@@ -49,6 +53,8 @@ shallow(Component, {
4953
有的时候你想要测试一个组件在配合 `$route``$router` 对象的参数时的行为。这时候你可以传递自定义假数据给 Vue 实例。
5054

5155
```js
56+
import { shallow } from 'vue-test-utils'
57+
5258
const $route = {
5359
path: '/some/path'
5460
}
@@ -59,7 +65,7 @@ const wrapper = shallow(Component, {
5965
}
6066
})
6167

62-
wrapper.vm.$router // /some/path
68+
wrapper.vm.$router.path // /some/path
6369
```
6470

6571
## 常识
@@ -68,4 +74,4 @@ wrapper.vm.$router // /some/path
6874

6975
这意味着在未来的任何测试中,伪造 `$route``$router` 都会失效。
7076

71-
要想回避这个问题,就不要在运行测试的时候安装 Vue Router。
77+
要想回避这个问题,就不要在运行测试的时候全局安装 Vue Router,而用上述的 `localVue` 用法

0 commit comments

Comments
 (0)