jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.04k stars 6.44k forks source link

[Feature]: add `expect(spy).toHaveResolvedWith` for spies on async functions #15188

Open plbstl opened 1 month ago

plbstl commented 1 month ago

🚀 Feature Proposal

Add a matcher for spies that spy on async functions.

Motivation

When spying on async functions, the received value of expect(spy).toHaveReturnedWith is always a Promise. This causes the tests to fail.

One way to go around this is to manually retrieve the Promise from the mock's metadata and await it.

See: https://github.com/plbstl/minimal-reproduction-jest-expect-tohavereturnedwith/blob/8e070ed6fb3757f5cf36a0550e1d6a5a31bebfd3/__tests__/index.test.ts#L14

It would be nice if expect(spy).toHaveReturnedWith automatically handles this or a new matcher (for example, toHaveResolvedWith) is created specifically for this use case.

Example

expect(asyncFunctionSpy).toHaveResolvedWith('expected')

Pitch

As helpful as the toHaveReturnedWith matcher when dealing with async code.

github-actions[bot] commented 4 weeks ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.

plbstl commented 3 weeks ago

...