如何通过jest

时间:2017-05-11 08:27:09

标签: redux react-redux jestjs

如何在我的组件的mapDispatchToProps中测试两个简单的操作。 我正在使用的测试命令是jest --coverage,它告诉我测试我的代码的下一行:

export const mapDispatchToProps = (dispatch) => {
    return {
---->   rightText: () => dispatch(rightText()),
---->   leftText: () => dispatch(leftText()),
    };
 };

如何编写测试以涵盖mapDispatchToProps内的这两个箭头函数?

1 个答案:

答案 0 :(得分:3)

我认为最简单的方法是将间谍传递给mapDispatchToProps然后你可以测试返回对象的功能:

const actionProps = mapDispatchToProps(spy)
// now you can test them
actionProps.rightText()
actionProps.leftText()

rightText()leftText()应该返回一个对象(如果它是同步的)。您还可以验证间谍中的操作对象(或者此处为mock)功能。

const mockDispatch = jest.fn()
const actionProps = mapDispatchToProps(mockDispatch)
actionProps.rightText()
actionProps.leftText()

// now you can verify the actions here
mockDispatch.mock.calls[0][0]
mockDispatch.mock.calls[1][0]

然后告诉您,您可以将普通对象传递给connect。在您的情况下,您可以简单地:

connect(mapStateToProps, {
  rightText,
  leftText
})(Component)