Skip to content

userEvent.click fails due to timeout when used with jest.useFakeTimers  #833

@fabrizzio-gz

Description

@fabrizzio-gz
  • @testing-library/user-event version: 14.0.0-beta.7
  • Testing Framework and version: jest version: 27.4.7, @testing-library/jest-dom version 5.15.1, @testing-library/react version 12.1.2
  • DOM Environment: jsdom version 19.0.0

Relevant code or config

// Dummy.js
import React from "react";

const Dummy = (props) => {
  const clickHandler = () => {
    setTimeout(() => {
      props.onClick();
    }, 500);
  };

  return <button onClick={clickHandler}>Click me</button>;
};

export default Dummy;
// Dummy.test.js
import React from "react";

import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import userEvent from "@testing-library/user-event";

import Dummy from "./Dummy";

// Fails
test("onClick prop is called on button (userEvent, fakeTimer)", async () => {
  jest.useFakeTimers();
  const user = userEvent.setup();
  const onClick = jest.fn();
  render(<Dummy onClick={onClick} />);

  const button = screen.getByRole("button");
  await user.click(button);
  jest.runOnlyPendingTimers();
  expect(onClick).toHaveBeenCalledTimes(1);
  jest.useRealTimers();
});

What you did:
Dummy component calls onClick prop after a delay when its button is clicked. I tried testing it using userEvent.click alongside jest.fakeTimers to avoid waiting for the delay.

What happened:
The test onClick prop is called on button (userEvent, fakeTimer) fails due to timeout.

npx jest output

 FAIL  client/src/dummy/Dummy.test.js (11.923 s)
  ✕ onClick prop is called on button (userEvent, fakeTimer) (5014 ms)

  ● onClick prop is called on button (userEvent, fakeTimer)

    thrown: "Exceeded timeout of 5000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

      19 |
      20 | // Fails
    > 21 | test.only("onClick prop is called on button (userEvent, fakeTimer)", async () => {
         |      ^
      22 |   jest.useFakeTimers();
      23 |   const user = userEvent.setup();
      24 |   const onClick = jest.fn();

      at Object.<anonymous> (client/src/dummy/Dummy.test.js:21:6)

Reproduction repository:
https://codesandbox.io/s/user-event-fake-timers-lwb65
(Source files are provided but I couldn't get the tests to run on codesandbox)

Problem description:

The test fails due to timeout. The problem arises when using jest.useFakeTimers. The line await user.click(button) never completes.

Suggested solution:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions