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

寵の児 提交于 2020-06-25 06:53:28

问题


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



  })

});



回答1:


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*/);
});



回答2:


import * as ReactRedux from 'react-redux'

describe('test', () => {
  it('should work', () => {
    const mockXXXFn = jest.fn()
    const spyOnUseDispatch = jest
      .spyOn(ReactRedux, 'useDispatch')
      .mockReturnValue({ xxxFn: mockXXXFn })

    // Do something ...

    expect(mockXXXFn).toHaveBeenCalledWith(...)

    spyOnUseDispatch.mockRestore()
  })
})

UPDATE: DO NOT use React Redux hooks API which is strongly coupling with Redux store implementation logic, make it very difficult to test.




回答3:


This is how I solved using react testing library:

I have this wrapper to render the components with Provider

export function configureTestStore(initialState = {}) {
  const store = createStore(
    rootReducer,
    initialState,
  );
  const origDispatch = store.dispatch;
  store.dispatch = jest.fn(origDispatch)

  return store;
}

/**
 * Create provider wrapper
 */
export const renderWithProviders = (
  ui,
  initialState = {},
  initialStore,
  renderFn = render,
) => {
  const store = initialStore || configureTestStore(initialState);

  const testingNode = {
    ...renderFn(
      <Provider store={store}>
        <Router history={history}>
          {ui}
        </Router>
      </Provider>
    ),
    store,
  };

  testingNode.rerenderWithProviders = (el, newState) => {
    return renderWithProviders(el, newState, store, testingNode.rerender);
  }

  return testingNode;
}

Using this I can call store.dispatch from inside the test and check if it was called with the action I want.

  const mockState = {
    foo: {},
    bar: {}
  }

  const setup = (props = {}) => {
    return { ...renderWithProviders(<MyComponent {...props} />, mockState) }
  };

  it('should check if action was called after clicking button', () => {
    const { getByLabelText, store } = setup();

    const acceptBtn = getByLabelText('Accept all');
    expect(store.dispatch).toHaveBeenCalledWith(doActionStuff("DONE"));
  });



回答4:


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!



来源:https://stackoverflow.com/questions/59018071/mock-usedispatch-in-jest-and-test-the-params-with-using-that-dispatch-action-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!