jestjs / jestjs/jest

Provide an API to flush the Promise resolution queue

Open
#2,157 65 comments 158 reactions 0 assignees View on GitHub
:rocket: Enhancement New API proposal
Dominant language
TypeScript
Stars
45.5k
Forks
6.7k
Avg merge
17h 22m
Merged PRs (30d)
24

Description

**Do you want to request a *feature* or report a *bug*?**

_Feature_, I guess, but a pretty important one when testing code that uses `Promise`s.

**What is the current behavior?**

I have a component that uses `Promise` wrapping and chaining internally in the follow-up to an external asynchronous action. I'm providing the mock of the async action and resolving the promise it returns in my test.

The component something like this:

```jsx
class Component extends React.Component {
// ...
load() {
Promise.resolve(this.props.load())
.then(
result => result
? result
: Promise.reject(/* ... */)
() => Promise.reject(/* ... */)
)
.then(result => this.props.afterLoad(result));
}
}
```

And the test code looks something like this:

```javascript
const load = jest.fn(() => new Promise(succeed => load.succeed = succeed));
const afterLoad = jest.fn();
const result = 'mock result';
mount();
// ... some interaction that requires the `load`
load.succeed(result);
expect(afterLoad).toHaveBeenCalledWith(result);
```

The test fails because the `expect()` is evaluated before the chained promise handlers. I have to replicate the length of the inner promise chain in the test to get what I need, like this:

```javascript
return Promise.resolve(load.succeed(result))
// length of the `.then()` chain needs to be at least as long as in the tested code
.then(() => {})
.then(() => expect(result).toHaveBeenCalledWith(result));
```

**What is the expected behavior?**

I'd expect Jest to provide some sort of an API to flush all pending promise handlers, e.g.:

```javascript
load.succeed(result);
jest.flushAllPromises();
expect(result).toHaveBeenCalledWith(result);
```

I've tried `runAllTicks` and `runAllTimers` to no effect.

---

_Alternatively, if I'm just missing some already existing feature or pattern, I'm hoping for someone here to point me in the right direction :)_

Contributor guide

Open the contributing guide

Research direction

Start by reviewing the existing runAllTicks and runAllTimers APIs and the issue discussion to determine how promise handlers differ from those queues. Done means a documented, reliable API flushes all pending promise handlers without requiring tests to reproduce the application's chain length.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
testing
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.