Skip to content

userEvent not working properly with jest.useFakeTimers #1034

@aakashsardana

Description

@aakashsardana
  • @testing-library/react version: 12.1.4
  • @testing-library/user-event version: 14.2.1
  • jest version: 26.6.3
  • react version: 16.14.0
  • node version: 14.17.4

Relevant code or config:

// App.js
import React, { useEffect, useState } from "react";

export default function App() {
  const [error, setError] = useState(null);

  useEffect(() => {
    let timeoutId;
    if (error) {
      timeoutId = setTimeout(() => {
        setError(null);
      }, 2500);
    }
    return () => {
      clearTimeout(timeoutId);
    };
  }, [error]);

  return (
    <div>
      <button onClick={() => setError("Something went wrong")}>Show error</button>
      <div>{error}</div>
    </div>
  );
}

// App.test.js

import React from "react";
import App from "./App";
import { render, screen, waitFor, act } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

test("shows error on button click and clears after some time", async () => {
  jest.useFakeTimers();
  render(<App />);
  const user = userEvent.setup();

  const errorBtn = screen.getByText(/show error/i);

  user.click(errorBtn);

  expect(screen.getByText(/something went wrong/i)).toBeInTheDocument();

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

  expect(screen.queryByText(/something went wrong/i)).not.toBeInTheDocument();
});

What you did:

Here we have a scenario that on clicking on a button we show some error and that error disappears after 2500ms. I am writing test cases for this scenario but when using jest.useFakeTimers with userEvent I am getting an error Timeout - Async callback was not invoked within the 5000ms . The interesting thing is this error does not come when I replace userEvent with fireEvent.

What happened:

jest-fakeTimers-error

Reproduction:

I am not able to create a CodeSandbox for this as jest.useFakeTimers is not supported by CodeSandbox but the code is working. One can simply copy and paste the code in their react project.

Problem description:

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