用玩笑测试分发功能

时间:2019-09-05 09:18:14

标签: reactjs jestjs enzyme

如何测试mapDispatchToProps的退货派发?

    export const mapDispatchToProps = (dispatch) => {
        return {
            sidebarSettings: () => {
                dispatch(showSettings)
            },
            setFilterText: (value) => {
                dispatch(setFilterText(value))
            },
            setExportCount: () => {
                dispatch(setExportCount())
            }
        }
    }

有此功能但不起作用...

describe('mapDispatchToProps', () => {
        test('should retrun a dispatch of sidebar settings, filter text and of export count', () => {
            const wrapper = shallow(<mapDispatchToProps />)
            expect(wrapper.find('dispatch')).toHaveLength(3)
        })
    })

3 个答案:

答案 0 :(得分:2)

这里是解决方案,mapDispatchToProps函数只是一个javascript函数。您无需使用Shallow的{​​{1}}渲染对其进行测试。

enzyme

单元测试:

const ACTION_TYPES = {
  SHOW_SETTINGS: 'SHOW_SETTINGS',
  SET_FILTER_TEXT: 'SET_FILTER_TEXT',
  SET_EXPORT_COUNT: 'SET_EXPORT_COUNT'
};

export const showSettings = { type: ACTION_TYPES.SHOW_SETTINGS };
export const setFilterText = value => ({ type: ACTION_TYPES.SET_FILTER_TEXT, payload: { value } });
export const setExportCount = () => ({ type: ACTION_TYPES.SET_EXPORT_COUNT });

export const mapDispatchToProps = dispatch => {
  return {
    sidebarSettings: () => {
      dispatch(showSettings);
    },
    setFilterText: value => {
      dispatch(setFilterText(value));
    },
    setExportCount: () => {
      dispatch(setExportCount());
    }
  };
};

覆盖率100%的单元测试结果:

import { mapDispatchToProps, showSettings, setFilterText, setExportCount } from './';

const dispatch = jest.fn();

describe('mapDispatchToProps', () => {
  it('t1', () => {
    const actualValue = mapDispatchToProps(dispatch);
    expect(Object.keys(actualValue)).toEqual(['sidebarSettings', 'setFilterText', 'setExportCount']);

    actualValue.sidebarSettings();
    expect(dispatch).toBeCalledWith(showSettings);

    actualValue.setFilterText('name');
    expect(dispatch).toBeCalledWith(setFilterText('name'));

    actualValue.setExportCount();
    expect(dispatch).toBeCalledWith(setExportCount());
  });
});

答案 1 :(得分:1)

mapDispatchToProps不是React组件,因此您无法渲染它。如果您真的想测试它是否返回了已定义的函数,而imo并没有多大意义,则只需检查对象是否具有已定义的props:

describe('mapDispatchToProps', () => {
  test('should retrun a dispatch of sidebar settings, filter text and of export count', () => {
    expect(Object.keys(mapDispatchToProps())).toHaveLength(3)
  })
})

答案 2 :(得分:1)

mapDispatchToProps不是React组件,您不需要酶来测试。 测试的一种方法是,您可以传递模拟调度并调用所有函数,并检查模拟调度是否被调用了多次。

describe('mapDispatchToProps', () => {
    const dispatch = jest.fn();
    const props = mapDispatchToProps(dispatch);
    props.setExportCount();
    props.setFilterText();
    props.sidebarSettings();
    expect(dispatch).toHaveBeenCalledTimes(3);
})