how properly mock multiple useSelector hooks

Viewed 5329

my component has multiple selectors:

import { useSelector } from 'react-redux'
...
const data1 = useSelector(xxxxx)
const data2 = useSelector(yyyyy)

How properly mock each in test file?

import { useSelector } from 'react-redux'
jest.mock('react-redux', () => ({
    useSelector: jest.fn()
}))
....
useSelector.mockImplementation(() => ({
   dataready: true
}))

which selector it's really mocking in this case?

2 Answers

Don't mock the selector. You want to test the integration between Redux and React components, not the Redux implementation of selectors. If you use react-testing-library it's pretty simple to hijack the render() method and implement your store using a Redux Provider component. Here are the docs for testing Connected Components.

Here's your test re-written with the user in mind:

import { render } from '../../test-utils' // <-- Hijacked render

it('displays data when ready', { // <-- behavior explanation
  const {getByTestId} = render(<YourComponent />, { 
    initialState: {
      dataready: true // <-- Pass data for selector
    }
  })
  expect(getByTestId('some-testId')).toBeTruthy(); // <-- Check that something shows based on selector
})

import * as redux from 'react-redux';
...
  beforeEach(() => {
    jest
      .spyOn(redux, 'useSelector')
      .mockReturnValueOnce(xxxx)
      .mockReturnValueOnce(yyyy);
  });
Related