如何测试调度功能?

时间:2019-09-09 09:13:11

标签: reactjs jestjs enzyme

您好,我正在尝试通过调用dispatch的返回次数来测试此功能,但实际上不知道如何正确地执行此功能才能调用{{1} }

dispatch

我有这些测试

export const mapDispatchToProps = (dispatch) => {
    return {
        hideSidebar: () => {
            dispatch(hideSidebar)
        },
        updateUnit: (unitObject) => {
            dispatch(settingsActions.updateArray(unitObject))
        }
    }
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

创建一个dispatch模拟函数并将其传递给mapDispatchToProps

然后调用在结果上定义的函数。

您可以使用类似toHaveBeenCalledWith的方法来验证是否已分派正确的操作:

// Stubs for hideSidebar and settingsActions.updateArray
const hideSidebar = { type: 'hide-side-bar' };
const settingsActions = { updateArray: u => ({ type: 'update-unit', payload: u })};

export const mapDispatchToProps = (dispatch) => {
  return {
    hideSidebar: () => {
      dispatch(hideSidebar)
    },
    updateUnit: (unitObject) => {
      dispatch(settingsActions.updateArray(unitObject))
    }
  }
}

test('mapDispatchToProps', () => {
  const dispatch = jest.fn();
  const map = mapDispatchToProps(dispatch);

  map.hideSidebar();
  expect(dispatch).toHaveBeenCalledWith({ type: 'hide-side-bar' });  // Success!

  map.updateUnit({ theKey: 'theVal' });
  expect(dispatch).toHaveBeenCalledWith({ type: 'update-unit', payload: { theKey: 'theVal' } });  // Success!
})