reactjs - 笑话:如何测试调用 bind(this) 的函数
问题描述
我有一个看起来像这样的父组件:
export class Header extends Component {
constructor(props) {
super(props)
this.state = { activeTab: TAB_NAMES.NEEDS_REVIEW }
}
filterByNeedsReview() {
const { filterByNeedsReviewFn } = this.props
this.setState({ activeTab: TAB_NAMES.NEEDS_REVIEW })
filterByNeedsReviewFn()
}
render() {
return (
...
<FilterTab
...
onClick={this.filterByNeedsReview.bind(this)}
/>
...
)
}
}
我正在尝试测试孩子是否装有正确的道具。最初我将它作为一个匿名函数:onClick={ () => this.filterByNeedsReview() }
但我无法对其进行测试,所以我尝试继续使用它bind(this)
。
但是,我在模拟bind
函数时遇到问题:
it('renders a filter tab with the right props for needs review', () => {
const bounded = jest.fn()
const boundedFilterByNeedsReview = jest.fn(() => {
return { bind: bounded }
})
Header.prototype.filterByNeedsReview = boundedFilterByNeedsReview
expect(
shallowRender()
.find(FilterTab)
.findWhere(node =>
_.isMatch(node.props(), {
... // other props
onClick: bounded, //<-------------- FAILS WHEN I ADD THIS LINE
})
)
).toHaveLength(1)
})
解决方案
在构造函数中绑定方法,防止每次组件渲染时重新绑定方法:
constructor(props) {
super(props)
this.state = { activeTab: TAB_NAMES.NEEDS_REVIEW }
this.filterByNeedsReview = this.filterByNeedsReview.bind(this)
}
然后将绑定的方法作为道具传递给孩子:
<FilterTab
...
onClick={this.filterByNeedsReview}
/>
您不需要在这里使用匿名函数。