Skip to content

Instantly share code, notes, and snippets.

@LauraBeatris
Last active October 30, 2023 11:48
Show Gist options
  • Save LauraBeatris/441de54d006da8bd51927a98bf8647bd to your computer and use it in GitHub Desktop.
Save LauraBeatris/441de54d006da8bd51927a98bf8647bd to your computer and use it in GitHub Desktop.
Jest mocks for React Redux
import { useSelector, useDispatch } from 'react-redux'
import { render, fireEvent } from '@testing-library/react';
// It can receive two more parameters, the second one is to specify a factory instead of the jest's automocking feature
jest.mock('react-redux')
it('should load some items in the component', () => {
// Returning a mock data from the store to test the behavior of the component
useSelector.mockImplementation((cb) => cb({items: ['Hello World']})
const { getByTestId } = render(<List />)
expect(getByTestId).toContainTextElement('Hello World')
)
it('should be able to add new item', () => {
const { getByTestId } = render(<List />)
// Unused mock function that can be used to custom implementations or to test calls
const dispatch = jest.fn()
// Every time that the useDispatch be called, it's gonna call the mock function
useDispatch.mockReturnValue(dispatch)
fireEvent.change(getByTestId('input', { target: { value: 'Hello World' } })
fireEvent.submit(getByTestId('form'))
expect(dispatch).toBeCalledWith({type: 'ADD_ITEM', payload: { item: 'Hello World'}})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment