score:3

Accepted answer

The component was trying to execute a function that wasn't declared yet. We need to mock before of the render method

const dispatch = jest.fn();
useDispatch.mockReturnValue(jest.fn());

const dropdown = render(<Dropdown />);

score:0

It is because when you mocked it, you haven't specified a value.

I thought of two ways to do this:

  1. Having a real store in your test, so you can test the integration:
const mockedStore = { /* the things you need in store in your test */ };
const store = configureStore(mockedStore, browserHistory);

const { getByTestId } = render(<Provider store={store}><Dropdown /></Provider>);
  1. Mock your dispatch, but you ll end up having infinite issues with useSelector (especially if you have more than one useSelector in the tree you rendered).
import * as ReactRedux from 'react-redux';

// useDispatch returns a function which we are mocking here
const mockDispatch = jest.fn();

beforeAll(() => {
  ReactRedux.useDispatch = jest.fn().mockImplementation(() => mockDispatch);
});

beforeEach(() => {
  ReactRedux.useDispatch.mockClear();
});


expect(mockDispatch).toHaveBeenCalledWith(yourAction);

Please note that the real issue you will face is not with dispatch, but with useSelector. If you mock it, it will return the value you want. But what if you have more than one in your tree ? for that, I real store is necessary as far as I know.


Related Query

More Query from same tag