Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock useSelector with different values

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?

like image 549
HMR Avatar asked Aug 31 '26 05:08

HMR


1 Answers

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))
like image 154
Paweł Gościcki Avatar answered Sep 02 '26 18:09

Paweł Gościcki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!