在酶浅渲染中将 jest.fn() 函数传递给 mapDispatchToProps

Fil*_*uzi 6 javascript jestjs redux enzyme redux-mock-store

有非常简单的组件:

从 'prop-types' 导入 PropTypes 从 'react' import { connect } from '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)
Run Code Online (Sandbox Code Playgroud)

我想测试 ifdoSth被调用 when shouldDoSthis equal true

我写了一个测试:

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()
  })
})
Run Code Online (Sandbox Code Playgroud)

但似乎虽然我将 doSth 作为 props 传递,但它会被mapDispatchToPropsasconsole.log('im not a mock')执行覆盖。

如何正确传递/覆盖/分配doSth函数以使组件使用模拟而不是来自mapDispatchToProps. 或者,也许我正在做一些根本不应该被允许的事情,并且有“适当”的方式来测试我的案例。我是否应该只模拟调度并检查它是否使用正确的参数调用?

Her*_*kov 3

我认为你需要弄清楚的一件事是你是否想doSth成为一个 prop,或者是一个连接在 mapDispatchToProps 中的 redux 动作。

如果它是一个 prop,那么您可以将它连接到父级(容器)中的 redux。将其从此组件的 mapDispatchToProps 中删除。这将使组件更易于测试。

如果你希望它是一个连接在这个组件中的redux操作,那么将这个操作移出这个组件是有意义的,比如在某个地方actions.js,将它导入到这个组件中,然后在测试中模拟它jest.mock('actions.js', () => ({doSth: jest.mock()}))