我正在尝试为去抖功能编写单元测试。我很难考虑这一点。
这是代码:
function debouncer(func, wait, immediate) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
if (!immediate) func.apply(this, args);
}, wait);
if (immediate && !timeout) func.apply(this, args);
};
}
Run Code Online (Sandbox Code Playgroud)
我应该如何开始?
我想知道如何使用 React 测试库和 Jest 测试间隔相关计时器在几次滴答后显示的内容。假设我们有这样的代码:
import React, { Component } from 'react';
let timer;
class Test extends Component {
constructor() {
super();
this.state = {
timeLeft: 60
}
}
componentDidMount() {
this.handleTick();
}
componentDidUpdate() {
const { timeLeft } = this.state;
if (!timeLeft) {
clearInterval(timer);
this.setState({
timeLeft: 60,
})
}
}
handleTick() {
timer = setInterval(() => {
this.setState({timeLeft: this.state.timeLeft - 1 })
},1000)
}
render() {
return (
<React.Fragment>
<h3>I'm test.</h3>
<h4>{this.state.timeLeft}</h4>
</React.Fragment>
)
}
}
Run Code Online (Sandbox Code Playgroud)
现在在测试中,我们想要检查测试组件是否在 15 秒后准确显示了我们想要的内容。我努力了: …