Reactjs 如何检查测试延迟后反应组件显示的内容
我想知道如何使用React测试库和Jest测试间隔相关计时器在几次滴答声后显示什么。 假设我们有这样的代码:Reactjs 如何检查测试延迟后反应组件显示的内容,reactjs,unit-testing,jestjs,react-testing-library,Reactjs,Unit Testing,Jestjs,React Testing Library,我想知道如何使用React测试库和Jest测试间隔相关计时器在几次滴答声后显示什么。 假设我们有这样的代码: import React, { Component } from 'react'; let timer; class Test extends Component { constructor() { super(); this.state = { timeLeft: 60 } } com
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>
)
}
}
到
它传递给。。。因此,它没有像我预期的那样工作。你对如何正确编写这个测试有什么想法吗?当然,我不想延迟我的测试。您可以使用将测试提前到num
毫秒。请记住,如果组件状态在该时间内更新,请将上述代码包装起来,以便React可以在断言之前正确地更新状态
test('计时器应显示剩余45秒',()=>{
开玩笑。使用faketimers();
const{getByText}=render();
行动(()=>{
笑话:提前计时(1500);
})
expect(getByText('45')).toBeInTheDocument();
})
非常感谢,这很有效!现在,我正试图在我的实际应用程序中实现这一点,我使用第三部分库react countdown circle timer
来显示countdown circletimer和remainingTime。它确实起作用,但我的计时器似乎在测试环境中没有滴答作响,这可能是另一个需要解决的问题。无论如何,谢谢你的时间:)它看起来像是react倒计时圈计时器
在引擎盖下使用的,而不是setTimeout
像你的问题一样。请参阅我的另一个答案,即使用现代实现设置假计时器,而不仅仅是模拟setTimeout
。希望它能解决你的问题@巴特·奥米耶图乔夫斯基
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();
expect(getByText('55')).toBeInTheDocument();