Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')



  })

});


like image 690
Shubham Singhal Avatar asked Nov 24 '19 13:11

Shubham Singhal


People also ask

How do you test for reducers in jest?

To test Reducers, you can call them with a specific input state and action and assert that the resulting state matches expectations. The following example tests reducers and also use actions implementation in it. We wrote this example in typescript.

What is the use of jest spyOn?

Jest's spyOn method is used to spy on a method call on an object. It is also very beneficial in cases where the Jest mock module or mock function might not be the best tool for the job on hand. While writing unit tests you only test one particular unit of code, generally a function.

Can you mock a component with jest?

This post gives examples of how to simply mock a React component in Jest. It will cover default and named exported components. I have previously written a piece on how to mock React components in Jest, and check to make sure that the component was passed specific props.

How do you mock a selector in react?

It takes two parameters: selector : Selector function to mock out return values for. mock : Jest mock function to call in place of the selector.


2 Answers

[upd] I've changed my mind dramatically since then. Now I think 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.

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*/);
});
like image 196
skyboyer Avatar answered Oct 21 '22 01:10

skyboyer


import * as redux from "react-redux";
describe('dispatch mock', function(){    
    it('should mock dispatch', function(){
            //arrange
            const useDispatchSpy = jest.spyOn(redux, 'useDispatch'); 
            const mockDispatchFn = jest.fn()
            useDispatchSpy.mockReturnValue(mockDispatchFn);

            //action
            triggerYourFlow();

            //assert
            expect(mockDispatchFn).toHaveBeenCalledWith(expectedAction);

            //teardown
            useDispatchSpy.mockClear();
    })
}});

From functional component we mock dispatch like above to stop it to execute the real implementation. Hope it helps!

like image 39
Yuvaraj Avatar answered Oct 21 '22 01:10

Yuvaraj