我想知道如何使用 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>
)
}
}
现在在测试中,我们想要检查测试组件是否在 15 秒后准确显示了我们想要的内容。
我努力了:
describe('Test Component', () => {
test('Timer should display 45 sec left', () => {
jest.useFakeTimers();
const { getByText } = render(<Test />);
setTimeout(() => {
expect(getByText('45')).toBeInTheDocument();
}, 15000);
jest.runAllTimers();
});
});
它通过了测试,但是如果我们更改代码行
expect(getByText('45')).toBeInTheDocument();
to
expect(getByText('55')).toBeInTheDocument();
它传递给...所以看起来它没有像我预期的那样工作。您对如何正确编写此测试有任何想法吗?我当然不想耽误我的考试。