gpt4 book ai didi

reactjs - 开 Jest : How to test function that calls bind(this)

转载 作者:行者123 更新时间:2023-12-03 14:12:20 24 4
gpt4 key购买 nike

我有一个如下所示的父组件:

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

我正在尝试测试 child 是否装载了正确的 Prop 。最初我将其作为匿名函数: 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)
})

最佳答案

在构造函数中绑定(bind)该方法,以防止每次组件渲染时重新绑定(bind)该方法:

constructor(props) {
super(props)
this.state = { activeTab: TAB_NAMES.NEEDS_REVIEW }
this.filterByNeedsReview = this.filterByNeedsReview.bind(this)
}

然后将绑定(bind)方法作为 prop 传递给子级:

<FilterTab
...
onClick={this.filterByNeedsReview}
/>

您不需要在此处使用匿名函数。

关于reactjs - 开 Jest : How to test function that calls bind(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52961039/

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