reactjsjestjsreact-hooksenzyme

mock useDispatch in jest and test the params with using that dispatch action in functional component


Hi I am writing test for functional component using the jest and enzyme. and When I simulate a click then params(state of component using useState) of component change. and when state is changed then useEffect call and in useEffect I am dispatching some asynchronous actions with params after changed. So I want to test params with I am dispatching the action. for this I want to mock dispatch. How can I achieve this ? Anyone can help me, thanks in advance. Below I am sharing the code.

component.js

import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { useSelector, useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { clientOperations, clientSelectors } from '../../store/clients';
import Breadcrumb from '../../components/UI/Breadcrumb/Breadcrumb.component';
import DataTable from '../../components/UI/DataTable/DataTable.component';
import Toolbar from './Toolbar/Toolbar.component';

const initialState = {
  search: '',
  type: '',
  pageNo: 0,
  rowsPerPage: 10,
  order: 'desc',
  orderBy: '',
  paginated: true,
};

const Clients = ({ history }) => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const totalElements = useSelector(state => state.clients.list.totalElements);
  const records = useSelector(clientSelectors.getCompaniesData);
  const [params, setParams] = useState(initialState);

  useEffect(() => {
    dispatch(clientOperations.fetchList(params));
  }, [dispatch, params]);

  function updateParams(newParams) {
    setParams(state => ({
      ...state,
      ...newParams,
    }));
  }

  function searchHandler(value) {
    updateParams({
      search: value,
      pageNo: 0,
    });
  }

  function typeHandler(event) {
    updateParams({
      type: event.target.value,
      pageNo: 0,
    });
  }

  function reloadData() {
    setParams(initialState);
  }

  const columns = {
    id: t('CLIENTS_HEADING_ID'),
    name: t('CLIENTS_HEADING_NAME'),
    abbrev: t('CLIENTS_HEADING_ABBREV'),
  };

  return (
    <>
      <Breadcrumb items={[{ title: 'BREADCRUMB_CLIENTS' }]}>
        <Toolbar
          search={params.search}
          setSearch={searchHandler}
          type={params.type}
          setType={typeHandler}
          reloadData={reloadData}
        />
      </Breadcrumb>
      <DataTable
        rows={records}
        columns={columns}
        showActionBtns={true}
        deletable={false}
        editHandler={id => history.push(`/clients/${id}`)}
        totalElements={totalElements}
        params={params}
        setParams={setParams}
      />
    </>
  );
};

Component.test.js

const initialState = {
  clients: {
    list: {
      records: companies,
      totalElements: 5,
    },
  },
  fields: {
    companyTypes: ['All Companies', 'Active Companies', 'Disabled Companies'],
  },
};

const middlewares = [thunk];
const mockStoreConfigure = configureMockStore(middlewares);
const store = mockStoreConfigure({ ...initialState });

const originalDispatch = store.dispatch;
store.dispatch = jest.fn(originalDispatch)

// configuring the enzyme we can also configure using Enjym.configure
configure({ adapter: new Adapter() });

describe('Clients ', () => {
  let wrapper;

  const columns = {
    id: i18n.t('CLIENTS_HEADING_ID'),
    name: i18n.t('CLIENTS_HEADING_NAME'),
    abbrev: i18n.t('CLIENTS_HEADING_ABBREV'),
  };

  beforeEach(() => {
    const historyMock = { push: jest.fn() };
    wrapper = mount(
      <Provider store={store}>
        <Router>
          <Clients history={historyMock} />
        </Router>
      </Provider>
    );
  });

 it('on changing the setSearch of toolbar should call the searchHandler', () => {
    const toolbarNode = wrapper.find('Toolbar');
    expect(toolbarNode.prop('search')).toEqual('')
    act(() => {
      toolbarNode.props().setSearch('Hello test');
    });
    toolbarNode.simulate('change');
****here I want to test dispatch function in useEffect calls with correct params"**
    wrapper.update();
    const toolbarNodeUpdated = wrapper.find('Toolbar');
    expect(toolbarNodeUpdated.prop('search')).toEqual('Hello test')



  })

});



Solution

  • Warning! This goes against best practices and recommendations from Redux team! Use this as a last resort!

    Mocking store(with redux-mock-store or even real store that changes its state) - and wrapping component with <Provider store={mockedStore}> - is way more reliable and convenient. Check another answer below.

    -- original answer below --

    if you mock react-redux you will be able to verify arguments for useDispatch call. Also in such a case you will need to re-create useSelector's logic(that's really straightforward and actually you don't have to make mock be a hook). Also with that approach you don't need mocked store or <Provider> at all.

    import { useSelector, useDispatch } from 'react-redux'; 
    
    const mockDispatch = jest.fn();
    jest.mock('react-redux', () => ({
      useSelector: jest.fn(),
      useDispatch: () => mockDispatch
    }));
    
    it('loads data on init', () => {
      const mockedDispatch = jest.fn();
      useSelector.mockImplementation((selectorFn) => selectorFn(yourMockedStoreData));
      useDispatch.mockReturnValue(mockedDispatch);
      mount(<Router><Clients history={historyMock} /></Router>);
      expect(mockDispatch).toHaveBeenCalledWith(/*arguments your expect*/);
    });