雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

react mock settimeout

2024-08-07 31

在 React 测试中,你可以使用 Jest 和测试工具库(如 React Testing Library)来模拟 setTimeout 函数的行为。以下是一个示例:

假设你有一个组件 DelayedComponent,其中包含一个在延迟后更新状态的函数:

import React, { useState } from 'react';

const DelayedComponent = () => {
  const [message, setMessage] = useState('');

  const handleClick = () => {
    setTimeout(() => {
      setMessage('Delayed message');
    }, 1000);
  };

  return (
    <div>
      <button onClick={handleClick}>Trigger Delay</button>
      <div>{message}</div>
    </div>
  );
};

export default DelayedComponent;

下面是如何在测试中模拟 setTimeout:

import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react';
import DelayedComponent from './DelayedComponent';

// Mocking setTimeout
jest.useFakeTimers();

test('DelayedComponent updates message after delay', async () => {
  const { getByText } = render(<DelayedComponent />);
  
  // Trigger the handleClick function
  fireEvent.click(getByText('Trigger Delay'));
  
  // Advance the timer by 1 second
  jest.advanceTimersByTime(1000);
  
  // Wait for the component to re-render
  await waitFor(() => getByText('Delayed message'));
  
  // Check if the message is updated
  expect(getByText('Delayed message')).toBeInTheDocument();
});

在上面的测试中,我们首先导入需要的测试工具,然后使用 jest.useFakeTimers() 来模拟 setTimeout 函数。接着,我们渲染了 DelayedComponent 组件,并触发了按钮点击事件,触发了 handleClick 函数。

然后,我们使用 jest.advanceTimersByTime(1000) 来模拟时间流逝了 1 秒,让 setTimeout 回调函数执行。接着,我们使用 await waitFor 等待组件重新渲染,然后检查更新后的消息是否正确显示在页面上。

这是一个简单的示例,你可以根据你的实际情况进行调整和扩展。

更新于:1个月前
赞一波!2

文章评论

全部评论