Skip to content

[code-infra] In react tests, clean up our act() #174

Open
@oliviertassinari

Description

@oliviertassinari

1. Don't wrap fireEvent with act

Example: https://github.com/mui/material-ui/blob/0bddcac5beeb535c36fa2055082cc8324e59c282/packages/mui-material/src/Button/Button.test.js#L612-L615

     );
     const button = getByRole('button');
 
+    fireEvent.keyDown(document.body, { key: 'TAB' });
     act(() => {
-      fireEvent.keyDown(document.body, { key: 'TAB' });
       button.focus();
     });

2. act should be awaited

As per mui/material-ui#41061 (comment)

From the docs:

We recommend using act with await and an async function. Although the sync version works in many cases, it doesn’t work in all cases and due to the way React schedules updates internally, it’s difficult to predict when you can use the sync version.
We will deprecate and remove the sync version in the future.

This is causing hard to debug issues. We should make our tests more robust and remove all sync usage of act.

     const button = getByRole('button');
 
     fireEvent.keyDown(document.body, { key: 'TAB' });
-    act(() => {
+    await act(async () => {
       button.focus();
     });

Also investigate if we can leverage eslint to discourage sync usage of act, see testing-library/eslint-plugin-testing-library#915

Search keywords:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions