DEV Community

Dennis Zhang
Dennis Zhang

Posted on

jest 关于定时器

在写测试文件时,有些组件使用了定时器,会影响测试判断,可以使用以下两个函数

1、jest.useFakeTimers()使用假定定时器
2、jest.runAllTimers() 将所有挂起的定时器运行,都完成

3、jest.advanceTimersByTime(ms):快进指定的时间
4、jest.runOnlyPendingTimers():仅运行挂起的定时器回调,而不是所有定时器。
5、jest.clearAllTimers():清除所有挂起的定时器

测试文件

// TimerComponent.test.jsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import TimerComponent from './TimerComponent';

test('updates message after timer completes', () => {
  // 使用假定时器
  jest.useFakeTimers();

  // 渲染组件
  render(<TimerComponent />);

  // 初始消息应该是 "Waiting..."
  expect(screen.getByText('Waiting...')).toBeInTheDocument();

  // 快进所有定时器
  jest.runAllTimers();

  // 断言定时器完成后消息更新
  expect(screen.getByText('Timer Completed!')).toBeInTheDocument();
});

Enter fullscreen mode Exit fullscreen mode

组件

// TimerComponent.jsx
import React, { useState, useEffect } from 'react';

const TimerComponent = () => {
  const [message, setMessage] = useState('Waiting...');

  useEffect(() => {
    const timer = setTimeout(() => {
      setMessage('Timer Completed!');
    }, 3000);

    return () => clearTimeout(timer);
  }, []);

  return <div>{message}</div>;
};

export default TimerComponent;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)