Stub/mock 用于测试的 propTypes

Stub/mock propTypes for testing

我的问题似乎很简单。代码工作正常,一切都很好,但是当我测试组件时,我收到此警告

Failed prop type: Controls: prop type onStatusChange is invalid; it must be a function, usually from React.PropTypes.in Controls

如果我从 onStatusChange 中删除 .isRequired,我不会收到任何警告。如何测试组件但保留 isRequired?为什么在我们从 parent?

传递字符串时,countdownStatus 道具没有出现相同的错误

在我的 child 控件组件中,我有这样的代码。我期待得到两个道具,一个字符串和一个函数。

class Controls extends Component {
  static propTypes = {
    countdownStatus: PropTypes.string.isRequired,
    onStatusChange: PropTypes.func.isRequired
  }
...
}

parent 组件中我有这个。如您所见,我正在向我的 child 传递两个道具,一个字符串和 function.This 道具函数可以从 child 组件内部调用,它将在 parrent 组件内部调用 handleStatusChange。

...
handleStatusChange = (newStatus: string) => {
    this.setState({
      countdownStatus: newStatus
    })
  }

  render (): React.Element<any> {
    const { count, countdownStatus } = this.state
    const renderControlArea = (): any => {
      if (countdownStatus !== 'stopped') {
        return <Controls countdownStatus={countdownStatus} onStatusChange={this.handleStatusChange} />
      } else {
        return <CountdownForm onSetCountdown={this.handleSetCountdown} />
      }
    }
    ...

child 组件测试。 我使用胶带,酶,sinon。 我什至不使用那个道具进行测试,我只是浅渲染整个组件。

test('Controls => should render pause button when countdownStatus equals started', (t: Object) => {
  t.plan(1)
  const wrapper: Object = shallow(<Controls countdownStatus={'started'} />)
  const pauseButton = wrapper.render().find('.btn-info').length
  t.equal(pauseButton, 1)
})

我找到了解决方案。我只需要在测试时将空虚拟函数作为道具传递。

test('Controls => should render pause button when countdownStatus equals started', (t: Object) => {
  t.plan(1)
  const wrapper: Object = shallow(<Controls countdownStatus={'started'} onStatusChange={() => {}}/>)
  const pauseButton = wrapper.render().find('.btn-info').length
  t.equal(pauseButton, 1)
})