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: docs/zh/guides/testing-async-components.md
+41-10Lines changed: 41 additions & 10 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,18 +1,49 @@
1
1
## 测试异步行为
2
2
3
-
为了让测试变得简单,`@vue/test-utils`*同步*应用 DOM 更新。不过当测试一个带有回调或 Promise 等异步行为的组件时,你需要留意一些技巧。
3
+
在编写测试代码时你将会遇到两种异步行为:
4
4
5
-
API 调用和 Vuex action 都是最常见的异步行为之一。下列例子展示了如何测试一个会调用到 API 的方法。这个例子使用 Jest 运行测试用例同时模拟了 HTTP 库 `axios`。更多关于 Jest 的手动模拟的介绍可移步[这里](https://jestjs.io/docs/zh-Hans/manual-mocks)。
在实践中,往往意味着你在更新会引发 DOM 变化的属性后必须使用 `Vue.nextTick()` 来等待 Vue 完成 DOM 更新。
15
+
16
+
使用 `Vue.nextTick()` 最简单的方法是在你的测试代码中使用异步函数:
17
+
18
+
```js
19
+
// 在文件头部引用Vue库
20
+
importVuefrom'vue'
21
+
22
+
// 其它的代码片断...
23
+
24
+
// 在测试框架中,编写一个测试用例
25
+
it('button click should increment the count text', async () => {
26
+
expect(wrapper.text()).toContain('0')
27
+
constbutton=wrapper.find('button')
28
+
button.trigger('click')
29
+
awaitVue.nextTick()
30
+
expect(wrapper.text()).toContain('1')
31
+
})
32
+
```
33
+
34
+
## 来自外部行为的更新
35
+
36
+
在 Vue 之外最常见的一种异步行为就是在 Vuex 中进行 API 调用。以下示例将展示如何测试在 Vuex 中进行 API 调用的方法。本示例使用 Jest 运行测试并模拟 HTTP 库`axios`。可以在[这里](https://jestjs.io/docs/en/manual-mocks.html#content)找到有关 Jest Mock 的更多信息。
37
+
38
+
`axios` Mock 的实现如下所示:
8
39
9
40
```js
10
41
exportdefault {
11
42
get: () =>Promise.resolve({ data:'value' })
12
43
}
13
44
```
14
45
15
-
下面的组件在按钮被点击的时候会调用一个 API,然后将响应的值赋给`value`。
46
+
当按钮被点击时,组件将会产生一个 API 调用,并且将响应的返回内容赋值给`value`。
16
47
17
48
```html
18
49
<template>
@@ -39,7 +70,7 @@ export default {
39
70
</script>
40
71
```
41
72
42
-
测试用例可以写成像这样:
73
+
可以这样编写测试:
43
74
44
75
```js
45
76
import { shallowMount } from'@vue/test-utils'
@@ -53,7 +84,7 @@ it('fetches async when a button is clicked', () => {
0 commit comments