-
Notifications
You must be signed in to change notification settings - Fork 20
Docs: Async behavior #37
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f6be1b7
docs: basic guide on async
lmiller1990 bbad888
docs: update link
lmiller1990 8079c53
Update src/guide/async-suspense.md
lmiller1990 33c6f6c
Update src/guide/async-suspense.md
lmiller1990 0dc2841
Update src/guide/async-suspense.md
lmiller1990 4e7ead0
Update src/guide/async-suspense.md
lmiller1990 5c18dd6
Update src/guide/async-suspense.md
lmiller1990 33a4f25
docs: async guide
lmiller1990 4e0f128
update gitignorE
lmiller1990 081dee9
Merge branch 'docs/async' of https://github.com/vuejs/vue-test-utils-…
lmiller1990 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,3 +11,4 @@ yarn-debug.log* | |
yarn-error.log* | ||
|
||
.idea | ||
.DS_Store |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,113 @@ | ||
# Suspense and Async Behavior | ||
# Asynchronous Behavior | ||
|
||
`async` related stuff. Maybe `flushPromises`? | ||
You may have noticed some other parts of the guide using `await` when calling some methods on `wrapper`, such as `trigger` and `setValue`. What's that all about? | ||
|
||
You might know Vue updates reactively; when you change a value, the DOM is automatically updated to reflect the latest value. Vue does this *asynchronously*. In contrast, a test runner like Jest runs *synchronously*. This can cause some surprising results in tests. Let's look at some strategies to ensure Vue is updating the DOM as expected when we run our tests. | ||
|
||
## A Simple Example - Updating with `trigger` | ||
|
||
Let's re-use the `<Counter>` component from [event handling](/guide/event-handling) with one change; we now render the `count` in the `template`. | ||
|
||
```js | ||
const Counter = { | ||
template: ` | ||
Count: {{ count }} | ||
<button @click="handleClick">Increment</button> | ||
`, | ||
data() { | ||
return { | ||
count: 0 | ||
} | ||
}, | ||
methods: { | ||
handleClick() { | ||
this.count += 1 | ||
} | ||
} | ||
} | ||
``` | ||
|
||
Let's write a test to verify the `count` is increasing: | ||
|
||
```js | ||
test('increments by 1', () => { | ||
const wrapper = mount(Counter) | ||
|
||
wrapper.find('button').trigger('click') | ||
|
||
expect(wrapper.html()).toContain('Count: 1') | ||
}) | ||
``` | ||
|
||
Surprisingly, this fails! The reason is although `count` is increased, Vue will not update the DOM until the next "tick" or "render cycle". For this reason, the assertion will be called before Vue updates the DOM. This has to do with the concept of "marcotasks", "microtasks" and the JavaScript Event Loop. You can read more details and see a simple example [here](https://javascript.info/event-loop#macrotasks-and-microtasks). | ||
|
||
Implementation details aside, how can we fix this? Vue actually provides a way for us to wait until the DOM is updated: `nextTick`: | ||
lmiller1990 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```js {7} | ||
import { nextTick } from 'vue' | ||
|
||
test('increments by 1', async () => { | ||
const wrapper = mount(Counter) | ||
|
||
wrapper.find('button').trigger('click') | ||
await nextTick() | ||
|
||
expect(wrapper.html()).toContain('Count: 1') | ||
}) | ||
``` | ||
|
||
Now the test will pass, because we ensure the next "tick" has executed updated the DOM before the assertion runs. Since `await nextTick()` is common, VTU provides a shortcut. Methods than cause the DOM to update, such as `trigger` and `setValue` return `nextTick`! So you can just `await` those directly: | ||
|
||
```js {4} | ||
test('increments by 1', async () => { | ||
const wrapper = mount(Counter) | ||
|
||
await wrapper.find('button').trigger('click') | ||
|
||
expect(wrapper.html()).toContain('Count: 1') | ||
}) | ||
``` | ||
|
||
## Resolving Other Asynchronous Behavior | ||
|
||
`nextTick` is useful to ensure some change in reactivty data is reflected in the DOM before continuing the test. However, sometimes you may want to ensure other, non Vue-related asynchronous behavior is completed, too. A common example is a function that returns a `Promise` that will lead to a change in the DOM. Perhaps you mocked your `axios` HTTP client using `jest.mock`: | ||
|
||
```js | ||
jest.mock('axios', () => ({ | ||
get: () => Promise.resolve({ data: 'some mocked data!' }) | ||
})) | ||
``` | ||
|
||
In this case, Vue has no knowledge of the unresolved Promise, so calling `nextTick` will not work - your assertion may run before it is resolved. For scenarios like this, you can use `[flush-promises](https://www.npmjs.com/package/flush-promises)`, which causes all outstanding promises to resolve immediately. | ||
|
||
Let's see an example: | ||
|
||
```js | ||
import flushPromises from 'flush-promises' | ||
lmiller1990 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import axios from 'axios' | ||
|
||
jest.mock('axios', () => ({ | ||
get: () => new Promise(resolve => { | ||
resolve({ data: 'some mocked data!' }) | ||
}) | ||
})) | ||
|
||
|
||
test('uses a mocked axios HTTP client and flush-promises', async () => { | ||
// some component that makes a HTTP called in `created` using `axios` | ||
const wrapper = mount(AxiosComponent) | ||
|
||
await flushPromses() // axios promise is resolved immediately! | ||
|
||
// assertions! | ||
}) | ||
|
||
``` | ||
|
||
lmiller1990 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
> If you haven't tested Components with API requests before, you can learn more in [HTTP Requests](/guide/http-requests). | ||
## Conclusion | ||
|
||
- Vue updates the DOM asynchronously; tests runner execute code synchronously. | ||
- Use `await nextTick()` to ensure the DOM has updated before the test continues | ||
- Functions that might update the DOM, like `trigger` and `setValue` return `nextTick`, so you should `await` them. | ||
- Use `flush-promises` to resolve any unresolved promises from non-Vue dependencies. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually… should these advanced concepts be mentioned before the "simple" solution of using
await
? It might be good to flip them: first the simple solution, and then, if anyone's interested, we can mention micro/macro tasks and add some interesting links.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure.
I dropped a link to an article by you about
nextTick
in there as well :)