gpt4 book ai didi

reactjs - 用于测试的 stub /模拟 propTypes

转载 作者:行者123 更新时间:2023-11-28 21:24:30 25 4
gpt4 key购买 nike

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

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

如果我从 onStatusChange 中删除 .isRequired,我不会收到任何警告。如何测试组件但保留 isRequired?为什么在我们从父级传递字符串的 countdownStatus 属性中没有得到相同的错误?

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

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

parent 组件里面我有这个。如您所见,我向我的 child 传递了两个 Prop ,一个字符串和一个函数。这个 Prop 函数可以从子组件内部调用,它将在父组件内部调用 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} />
}
}
...

子组件测试。我使用胶带, enzyme ,sinon。我什至不使用该 Prop 进行测试,我只是浅渲染整个组件。

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)
})

最佳答案

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

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)
})

关于reactjs - 用于测试的 stub /模拟 propTypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43945268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com