如何在测试延迟后检查反应组件显示的内容 [英] How to check what react component displays after delay in a test

查看:12
本文介绍了如何在测试延迟后检查反应组件显示的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用 React 测试库和 Jest 测试间隔相关计时器显示的内容.假设我们有这样的代码:

I was wondering how to test what does interval dependant timer display after a few ticks with React Testing Library and Jest. Assume we have such code:

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 秒后准确显示了我们想要的内容.我试过了:

And now in test we want to check if Test component shows exactly what we want after let's say 15 sec. I have tried:

describe('Test Component', () => {
  test('Timer should display 45 sec left', () => {
    jest.useFakeTimers();
    const { getByText } = render(<Test />);
    setTimeout(() => {
      expect(getByText('45')).toBeInTheDocument();
    }, 15000);
    jest.runAllTimers();
  });
});

它通过了测试,但是如果我们改变代码行

It pass the test, but if we change code line from

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

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

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

it passes to... So it seams that it doesn't work as I was expected. Do you have any ideas how to write this test properly? Of course I don't want to delay my tests.

推荐答案

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

You can use jest.advanceTimersByTime(num) to advance by num milliseconds to the future. Remember to wrap the code above in act() if the component state is updated in that time so React can update the state properly before the assertion.

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

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

这篇关于如何在测试延迟后检查反应组件显示的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆