Skip to content

Instantly share code, notes, and snippets.

@LauraBeatris
Created April 8, 2020 10:11
Show Gist options
  • Save LauraBeatris/598c489bd8f851ff3851a39f556dc18b to your computer and use it in GitHub Desktop.
Save LauraBeatris/598c489bd8f851ff3851a39f556dc18b to your computer and use it in GitHub Desktop.
Jest mocks for React Redux
import { useSelector, useDispatch } from 'react-redux'
// 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