I'm trying something like this:
const useSelector = jest.fn();
jest.mock('react-redux', () => ({
useSelector,
}));
Then trying to do something like this:
useSelector.mockReturnValueOnce({});
shallow(
<ComponentUsingUseSelector />
);
That will give me an error:
The module factory of
jest.mock()is not allowed to reference any out-of-scope variables.
So if I can't use an out of scope variable for a mock then how would I return a different value for every test?
Simplified version, which also works:
import * as redux from 'react-redux'
jest
.spyOn(redux, 'useSelector')
.mockReturnValueOnce('first call')
Also, instead of relying on multiple calls to mockReturnValueOnce it's better to just stub the necessary part of the store:
const locale = 'en'
const state = {
application: { locale },
}
jest
.spyOn(redux, 'useSelector')
.mockImplementation((callback) => callback(state))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With