【发布时间】:2018-10-08 04:50:35
【问题描述】:
我正在使用 Jest 和 Enzyme 测试一个 React 组件,并且在测试去抖动函数是否被正确调用(或完全调用)时遇到了困难。我已经简化了下面的组件代码(经过编辑使代码更简单),链接到 codepen here
// uses lodash debounce
class MyApp extends React.Component {
constructor(props) {
super()
this.state = {name: "initial value"};
this.debouncedFunction = _.debounce(this.debouncedFunction, 3000);
this.handleClick = this.handleClick.bind(this)
}
debouncedFunction () {
this.setState({name: "after delay, updated value"});
}
handleClick() {
this.debouncedFunction();
}
render() {
return (
<div>
<p>{this.state.name}</p>
<button onClick={this.handleClick}>
click for debounced function
</button>
</div>
);
}
}
我认为去抖功能测试应该与非去抖功能测试非常相似,但带有setTimeout 或Promise(expect 断言在.then 或.finally 内)。在尝试了使用这两种想法的许多测试变体之后,我不再那么确定了。有什么想法吗?
【问题讨论】:
-
您可能需要使用this 模拟计时器并使用
jest.advanceTimersByTime()。如果你能提供一个我可以编写和调试测试的设置,我可以尝试一些方法并分享一个解决方案。 -
感谢您的帮助!我简化了我的代码示例,并在上面的问题中添加了一个 codepen 链接。
-
谢谢。但由于 jest 不在浏览器中运行,我将无法编写和验证测试。也许过一段时间我会试试。但是我找到了一个符合我想法的答案。看看stackoverflow.com/a/52226973/2950032
-
我不确定这是否只是出于显示目的的简化,但您的处理程序很容易在构造函数中只是
this.handleClick = _.debounce(this.handleClick.bind(this), 3000);。然后,一切都正确绑定,您可以单独测试点击处理程序。
标签: javascript reactjs jestjs enzyme