【发布时间】:2018-12-02 01:05:35
【问题描述】:
有非常简单的组件:
从“prop-types”导入 PropTypes 从“反应”导入反应 从'react-redux'导入{连接}
class MyComponent extends React.Component {
componentWillMount() {
if (this.props.shouldDoSth) {
this.props.doSth()
}
}
render () {
return null
}
}
MyComponent.propTypes = {
doSth: PropTypes.func.isRequired,
shouldDoSth: PropTypes.bool.isRequired
}
const mapStateToProps = (state) => {
return {
shouldDoSth: state.shouldDoSth,
}
}
const mapDispatchToProps = (dispatch) => ({
doSth: () => console.log('you should not see me')
})
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
我想测试当shouldDoSth 等于true 时是否调用doSth。
我写了一个测试:
describe('call doSth when shouldDoSth', () => {
it('calls doSth', () => {
const doSthMock = jest.fn()
const store = mockStore({shouldDoSth: true})
shallow(<MyComponent doSth={doSthMock}/>, { context: { store } }).dive()
expect(doSthMock).toHaveBeenCalled()
})
})
但似乎虽然我将 doSth 作为道具传递,但在执行 console.log('im not a mock') 时,它会被 mapDispatchToProps 覆盖。
如何正确传递/覆盖/分配doSth 函数以使组件使用模拟而不是mapDispatchToProps 中的函数。或者,也许我正在做一些根本不应该被允许的事情,并且有“正确”的方式来测试我的案例。我应该只模拟调度并检查它是否使用正确的参数调用?
【问题讨论】:
标签: javascript redux jestjs enzyme redux-mock-store