Skip to content

Improve docs to avoid 'act' warning when using react-query in tests #432

Closed
@dustinsoftware

Description

@dustinsoftware

This is sort of related to #270. Filing in case we can improve the docs to help others avoid this issue.

When running tests, I ran into this error:

console.error node_modules/react-dom/cjs/react-dom.development.js:88
    Warning: An update to _default inside a test was not wrapped in act(...).

Here's the test:

test('renders the component', async () => {
  await act(async () => {
    const { getByText } = render(<Component />);
    const linkElement = getByText(/Hello/i);
    expect(linkElement).toBeInTheDocument();
  });
});

And here's the component (simplified):

const getPing = async () => {
  const { data } = await axios.get<{ content: string }>(
    getRoutePrefix() + 'ping'
  );
  return data;
};

export default function () {
  const { status, data, error, isFetching } = useQuery('ping', getPing);

  return (
    <>
      <div>Hello!</div>

      <div>{JSON.stringify(status)}</div>
      <div data-testid="testdata">{JSON.stringify(data)}</div>
      <div>Err: {JSON.stringify(error)}</div>
      <div>{JSON.stringify(isFetching)}</div>
    </>
  );
}

In #271 there was some cleanup logic added, however the error in my case appears to have been thrown before the cleanup call was fired.

I can fix the issue by adding to my tests at the end of each act call:

- import { render, wait } from '@testing-library/react';
+ import { render, wait, cleanup } from '@testing-library/react';

test('renders the component', async () => {
  await act(async () => {
    const { getByText } = render(<Component />);
    const linkElement = getByText(/Hello/i);
    expect(linkElement).toBeInTheDocument();
+   cleanup();
  });
});

Doing the cleanup outside the act does not help; that appears to be too late.

Is it necessary to add the cleanup call inside every act call? If so, can we update the react-query docs on how to test with jest + react-testing-library? I bet others will run into this issue as well and hoping to save some time as more users adopt the library.

Here's some screenshots with a debugger attached indicating the warning is originally caused by a call to refetch:
Screen Shot 2020-05-01 at 12 07 49
Screen Shot 2020-05-01 at 12 18 59
Screen Shot 2020-05-01 at 12 11 30

Versions:

@testing-library/react@9.5.0
jest@24.9.0
miragejs@0.1.37
react-dom@16.13.1
react-query@1.2.9
react-scripts@3.4.1
react@16.13.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions