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/en/guides/testing-async-components.md
+10-10
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,10 @@
1
-
# 测试异步行为
1
+
# Testing Asynchronous Behavior
2
2
3
-
为了让测试变得简单,`vue-test-utils`_同步_应用 DOM 更新。不过当测试一个带有回调或 Promise 等异步行为的组件时,你需要留意一些技巧。
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
4
5
-
API 调用和 Vuex action 都是最常见的异步行为之一。下列例子展示了如何测试一个会调用到 API 的方法。这个例子使用 Jest 运行测试用例同时模拟了 HTTP 库`axios`。更多关于 Jest 的手动模拟的介绍可移步[这里](https://facebook.github.io/jest/docs/en/manual-mocks.html#content)。
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
6
7
-
`axios`的模拟实现大概是这个样子的:
7
+
The implementation of the `axios`mock looks like this:
8
8
9
9
```js
10
10
exportdefault {
@@ -14,7 +14,7 @@ export default {
14
14
}
15
15
```
16
16
17
-
下面的组件在按钮被点击的时候会调用一个 API,然后将响应的值赋给 `value`。
17
+
The below component makes an API call when a button is clicked, then assigns the response to `value`.
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.
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.
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
78
79
79
The updated test looks like this:
80
80
@@ -94,4 +94,4 @@ test('Foo', () => {
94
94
})
95
95
```
96
96
97
-
相同的技巧可以被运用在同样默认返回一个 Promise 的 Vuex action 中。
97
+
This same technique can be applied to Vuex actions, which return a promise by default.
0 commit comments