Skip to content

Commit b91eef0

Browse files
gnapsealexkrolick
authored andcommitted
docs: add FAQ section about how flushPromises work (closes testing-library#11) (testing-library#15)
* Add FAQ section about how flushPromises work * Some subtle changes
1 parent 9a04ff6 commit b91eef0

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

packages/react-testing-library/README.md

+22
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,27 @@ That's not to say that there's never a use case for doing those things, so they
345345
should be possible to accomplish, just not the default and natural way to test
346346
react components.
347347

348+
**How does `flushPromises` work and why would I need it?**
349+
350+
As mentioned [before](#flushpromises), `flushPromises` uses
351+
[`setImmediate`][set-immediate] to schedule resolving a promise after any pending
352+
tasks in
353+
[the message queue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)
354+
are processed. This includes any promises fired before in your test.
355+
356+
If there are promise callbacks already in JavaScript's message queue pending to be
357+
processed at the time `flushPromises` is called, then these will be processed before
358+
the promise returned by `flushPromises` is resolved. So when you
359+
`await flushPromises()` the code immediately after it is guaranteed to occur after
360+
all the side effects of your async requests have ocurred. This includes any data
361+
your test components might have requested.
362+
363+
This is useful for instance, if your components perform any data requests and update
364+
their state with the results when the request is resolved. It's important to note
365+
that this is only effective if you've mocked out your async requests to resolve
366+
immediately (like the `axios` mock we have in the examples). It will not `await`
367+
for promises that are not already resolved by the time you attempt to flush them.
368+
348369
## Other Solutions
349370

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

0 commit comments

Comments
 (0)