Test fails when mock function returns rejected Promise
See original GitHub issue🐛 Bug Report
The following test fails because a rejected Promise is set as return value:
test("My test", async () => {
const myMockFunc = jest.fn().mockReturnValueOnce(Promise.reject("error"))
setTimeout(() => myMockFunc(), 100)
await new Promise(resolve => setTimeout(resolve, 200))
expect(myMockFunc.mock.calls.length).toBe(1)
})
Expected behavior
The test should pass. If e.g. a resolved Promise is returned it passes.
How to reproduce
Execute the test above.
Run npx envinfo --preset jest
System:
OS: macOS 10.14.3
CPU: (8) x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
Binaries:
Node: 11.12.0 - /usr/local/bin/node
npm: 6.7.0 - /usr/local/bin/npm
npmPackages:
jest: ^24.5.0 => 24.5.0
Issue Analytics
- State:
- Created 4 years ago
- Reactions:5
- Comments:6 (1 by maintainers)
Top Results From Across the Web
How to mock a promise rejection with Jest - Stack Overflow
I wrote this test that checks the signUp method in an repository class. The problem is that in order to trigger the exceptions...
Read more >Testing promise rejection in JavaScript with Jest - Codeleak.pl
Let's consider a simple function that returns a Promise that can either resolve or reject depending on the value of the first argument:...
Read more >Testing promise rejection in JavaScript with Jest
Let's consider a simple function that returns a Promise that can either resolve or reject depending on the value of the first argument:...
Read more >Testing Asynchronous Code · Jest
Just return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test...
Read more >API Reference | Vitest
When a test function returns a promise, the runner will wait until it is resolved to collect async expectations. If the promise is...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Because using
Promise.reject()will create a rejected promise immediately, a rejected promise without catch will throw an error, so the test fails.You can return rejected promise like below. It create a rejected promise when you call this function, instead of in the declaration.
The test will look like:
Thank you for your clarification. That cleared things up for me a lot. Thank you for this amazing test framework!