Skip to content

Add FAQ section about how flushPromises work (closes #11) #15

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 2 commits into from
Mar 22, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,27 @@ That's not to say that there's never a use case for doing those things, so they
should be possible to accomplish, just not the default and natural way to test
react components.

**How does `flushPromises` work and why would I need it?**

As mentioned [before](#flushpromises), `flushPromises` uses
[`setImmediate`][set-immediate] to schedule resolving a promise after any pending
tasks in
[the message queue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)
are processed. This includes any promises fired before in your test.

If there are promise callbacks already in JavaScript's message queue pending to be
processed at the time `flushPromises` is called, then these will be processed before
the promise returned by `flushPromises` is resolved. So when you
`await flushPromises()` the code immediately after it is guaranteed to occur after
all the side effects of your async requests have ocurred. This includes any data
your test components might have requested.

This is useful for instance, if your components perform any data requests and update
their state with the results when the request is resolved. It's important to note
that this is only effective if you've mocked out your async requests to resolve
immediately (like the `axios` mock we have in the examples). It will not `await`
for promises that are not already resolved by the time you attempt to flush them.

## Other Solutions

In preparing this project,
Expand Down Expand Up @@ -421,3 +442,4 @@ MIT
[twitter-badge]: https://img.shields.io/twitter/url/https/github.com/kentcdodds/react-testing-library.svg?style=social
[emojis]: https://github.com/kentcdodds/all-contributors#emoji-key
[all-contributors]: https://github.com/kentcdodds/all-contributors
[set-immediate]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate