mockRejectedValueOnce() fails to replace default return value
See original GitHub issue🐛 Bug Report
mockRejectedValueOnce()
fails to replace default return value in v23.3.0
To Reproduce
const mock = jest.fn().mockReturnValue(Promise.resolve(10));
it('test', () => {
mock.mockRejectedValueOnce(20);
return expect(mock()).rejects.toBe(20);
});
Expected behavior
Test passes
Actual behavior
● test
expect(received).rejects.toBe()
Expected received Promise to reject, instead it resolved to value
10
2 | it('test', () => {
3 | mock.mockRejectedValueOnce(20);
> 4 | return expect(mock()).rejects.toBe(20);
| ^
5 | });
6 |
Workaround
Set default return value with mockImplementation()
or mockResolvedValue()
const mock = jest.fn().mockImplementation(() => Promise.resolve(10));
or
const mock = jest.fn().mockResolvedValue(10);
Issue Analytics
- State:
- Created 5 years ago
- Reactions:4
- Comments:6
Top Results From Across the Web
mockRejectedValueOnce is not a function - Stack Overflow
I resolved above by changing above code mockRejectedValueOnce to mockImplementation: getMessages.mockImplementation(() ...
Read more >Mock Functions - Jest
You can create a mock function with jest.fn() . If no implementation is given, the mock function will return undefined when invoked.
Read more >jest-when - npm
If you want to change the return value based on the arguments, you have to use mockImplementation and it can be a bit...
Read more >Simplifying TypeScript code with Jest mocking
My function should call all 3 of them and return an array of the return values like this: const getAll = () =>...
Read more >Mock Functions - Jest 中文文档
If no implementation is given, the mock function will return undefined when ... mockClear() will replace mockFn.mock , not just reset the values...
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 FreeTop 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
Top GitHub Comments
I’m having precisely the same issue in an async setting, too. It seems none of the
mock...Once
functions are working as expected.UPDATE: It turns out, I was not marking my
beforeAll()
method async, which was the cause of the instability. I’m in v23.5.0, though, so perhaps this is still broken in v23.3.0This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.