如何检查测试延迟后反应组件显示的内容

2023-11-29

我想知道如何使用 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();

它传递给...所以看起来它没有像我预期的那样工作。您对如何正确编写此测试有任何想法吗?我当然不想耽误我的考试。


您可以使用jest.advanceTimersByTime(num)前进num未来的几毫秒。记得将上面的代码包裹起来act()如果组件状态在那段时间更新,那么 React 可以在断言之前正确更新状态。

test('Timer should display 45 sec left', () => {
  jest.useFakeTimers();
  const { getByText } = render(<Test />);

  act(() => {
    jest.advanceTimersByTime(1500);
  })
  expect(getByText('45')).toBeInTheDocument();
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查测试延迟后反应组件显示的内容 的相关文章

随机推荐