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

How to check what react component displays after delay in a test

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

expect(getByText('55')).toBeInTheDocument();

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

如果组件状态在那个时候更新,您可以使用 jest.advanceTimersByTime(num) to advance by num milliseconds to the future. Remember to wrap the code above in act(),以便 React 可以在断言之前正确更新状态。

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

  act(() => {
    jest.advanceTimersByTime(1500);
  })
  expect(getByText('45')).toBeInTheDocument();
})