具有非常简单的组件:
从“prop-types”导入 PropTypes 从“ react ”导入 react 从'react-redux'导入{connect}
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 作为 Prop 传递,但它被 mapDispatchToProps
覆盖,因为 console.log('im not a mock')
被执行。
如何正确传递/覆盖/分配 doSth
函数以使组件使用 mock 而不是 mapDispatchToProps
中的函数。或者也许我正在做一些根本不应该被允许的事情,并且有“正确”的方式来测试我的案例。我应该只模拟调度并检查是否使用正确的参数调用它吗?
最佳答案
我认为您需要弄清楚的一件事是您是希望 doSth
成为一个 Prop ,还是在 mapDispatchToProps 中连接的 redux Action 。
如果它是一个 prop,那么您可以将它连接到父级(容器)中的 redux。将其从该组件的 mapDispatchToProps 中移除。这将使组件更易于测试。
如果你想让它成为一个连接在这个组件中的redux action,那么把这个action移出这个组件是有意义的,比如actions.js
,将它导入到这个组件中,然后在测试中模拟它 jest.mock('actions.js', () => ({doSth: jest.mock()}))
关于javascript - 在 enzyme 浅渲染中将 jest.fn() 函数传递给 mapDispatchToProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50989868/