Skip to content

waitFor with getAllBy query not equivalent to findAllBy #1225

@Clarity-89

Description

@Clarity-89
  • @testing-library/dom version: 9.2.0
  • Testing Framework and version:
    • "@testing-library/react": "14.0.0",
    • Jest: "29.5.0"
  • DOM Environment:

Also using React 18.

Relevant code or config:

import { act, render, screen, waitFor } from "@testing-library/react";
import { TestComponent } from "./App";

const mockDataProvider = {
  start: jest.fn().mockImplementation(() => Promise.resolve()),
  getKeys: () => ["key1", "key2"],
};
const props = {
  dataProvider: mockDataProvider,
  updateFilter: jest.fn(),
  item: {
    entry: "Sample entry",
    attributes: {
      key1: "value1",
      key3: "value3",
    },
  },
};

describe("Test", () => {
  it("Passing test", async () => {
    jest.useFakeTimers();
    render(<TestComponent {...props} />);
    await waitFor(() => {
      expect(props.dataProvider.start).toHaveBeenCalled();
      expect(screen.getAllByRole("alert")).toHaveLength(2);
    });
    act(() => {
      jest.runAllTimers();
    });
    expect(props.updateFilter).toHaveBeenCalled();
    jest.useRealTimers();
  });

  it("Failing test", async () => {
    jest.useFakeTimers();
    render(<TestComponent {...props} />);

    await waitFor(() => {
      expect(props.dataProvider.start).toHaveBeenCalled();
    });
    expect(await screen.findAllByRole("alert")).toHaveLength(2);
    act(() => {
      jest.runAllTimers();
    });
    expect(props.updateFilter).toHaveBeenCalled();
    jest.useRealTimers();
  });
});

What you did:

What happened:

The first test succeeds while the seconds test fails.

Reproduction:

Codesandbox

Problem description:

Not sure if this is an actual bug, but I can't understand why the combination of awaitFor + getAllByRole passes the test but using findAllByRole doesn't. Aren't findBy* queries just a wrapper for awaitFor + getBy*? Also the second test doesn't really need the mock timers, but I've included those to make the tests more comparable (it doesn't change the test result).

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