How to mock multiple useSelectors (react redux) in Jest
Daisho Komiyama edited this page Sep 3, 2022
·
1 revision
When writing tests, creating API mocks is necessary, but it is sometimes very painful, especially since there are multiple selectors in the target component and its children.
I'm leaving a note for myself. Here's the tech stack.
- Jest
- react-redux
We have two selectors defined in respective files.
store/config/selectors.js
export const getConfig = state => state?config
store/blog/selectors.js
export const getBlogPosts = state => state?blogPosts
There are three steps in a test suite.
- import the selectors
- set them to jest mock
- use them
// import selectors
import { getConfig } from 'store/config/selectors'
import { getBlogPosts } from 'store/blog/selectors'
// set them to mock
jest.mock('store/config/selectors')
jest.mock('store/blog/selectors')
// use them in test scenarios. Set desired return value to the callback function of `mockImplementation`.
beforeEach(() => {
getConfig.mockImplementation(() => { lang: 'en' })
getBlogPosts.mockImplementation(() => [{...}, {...}])
})
That's it. You should see the return values when you run the test.