useFakeTimers 在 jest/testing-library 中不起作用

我正在渲染一个使用 setTimeout 将内部文本从加载状态更改为所需消息的元素:

function Message({ message }: any) {
  const [showMessage, setShowMessage] = useState(false);

  useEffect(() => {
    const CTATimer = setTimeout(() => {
      setShowMessage(true);
    }, 1500);
    return () => {
      clearTimeout(CTATimer);
    };
  }, []);

  if (!showMessage) {
    return <p>Loading...</p>;
  }

  return (
    <>
      <div>{message.text}</div>
    </>
  );
}

相应的测试呈现,然后将时间提前 1500 毫秒,然后应该显示消息。但是,目前测试失败,终端显示文本仍然是 Loading... 。测试是这样写的:

const mockMessage = {
  text: "this is a message",
  answers: [],
  id: 1,
};

afterEach(() => {
  jest.useRealTimers();
});

it("should show message after setTimeout", () => {
  jest.useFakeTimers();
  jest.advanceTimersByTime(1500);
  customRender(<Message message={mockMessage} />); // my customRender is just the default render but with a ThemeProvider wrapper.
  const message = screen.getByText(/this is a message/i);
  expect(message).toBeInTheDocument();
});

为什么我的测试在 1500 毫秒过去后仍然呈现加载状态?

stack overflow useFakeTimers not working in jest/testing-library
原文答案
author avatar

接受的答案

您应该在渲染组件后提前计时器。此外,您应该在 jest.advanceTimersByTime() 函数中调用 act 。否则,它会抛出一个警告: Warning: An update to Message inside a test was not wrapped in act(...).

index.tsx

import React from 'react';
import { useEffect, useState } from 'react';

export function Message({ message }: any) {
  const [showMessage, setShowMessage] = useState(false);

  useEffect(() => {
    const CTATimer = setTimeout(() => {
      setShowMessage(true);
    }, 1500);
    return () => {
      clearTimeout(CTATimer);
    };
  }, []);

  if (!showMessage) {
    return <p>Loading...</p>;
  }

  return (
    <>
      <div>{message.text}</div>
    </>
  );
}

index.test.tsx

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

describe('Message', () => {
  const mockMessage = {
    text: 'this is a message',
    answers: [],
    id: 1,
  };

  afterEach(() => {
    jest.useRealTimers();
  });

  it('should show message after setTimeout', () => {
    jest.useFakeTimers();
    render(<Message message={mockMessage} />);
    act(() => {
      jest.advanceTimersByTime(1500);
    });
    const message = screen.getByText(/this is a message/i);
    expect(message).toBeInTheDocument();
  });
});

测试结果:

 PASS  stackoverflow/71174071/index.test.tsx (9.705 s)
  Message
    ✓ should show message after setTimeout (27 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.903 s
Ran all test suites related to changed files.

答案:

作者头像

如果使用异步测试,因为您需要使用 userEvent 进行打字等。我在这个博客上找到了一个解决方案: https://onestepcode.com/testing-library-user-event-with-fake-timers/

诀窍是将 delay 上的 userEvent 选项设置为 null

const user = userEvent.setup({ delay: null });

这是一个完整的测试用例

test("Pressing the button hides the text (fake timers)", async () => {
    const user = userEvent.setup({ delay: null });
    jest.useFakeTimers();

    render(<Demo />);

    const button = screen.getByRole("button");
    await user.click(button);

    act(() => {
        jest.runAllTimers();
    });

    const text = screen.queryByText("Hello World!");
    expect(text).not.toBeInTheDocument();

    jest.useRealTimers();
});