Skip to content

Having to use an empty act immediately after render to avoid warning #1066

Closed as not planned
@leepowellnbs

Description

@leepowellnbs

I have a component, which does some async loading of data from various sources - some coming from within the component itself, and some coming from a wrapped context - all take place in useEffect hooks. I'm finding I'm having to use empty act calls to avoid the act warning - contrived example:

const screen = render(<MyComponent />, { wrapper: <MyContextProviders />});

expect(await screen.findByText('Hello')).toBeTruthy();

In this example I get the "not wrapped in an act" warning from where one of the context providers is fetching data on mount. The odd thing, is the component doesn't render Hello until this data fetching is finished and the fetched data is available.

To suppress the error I am having to add an empty act:

const screen = render(<MyComponent />, { wrapper: <MyContextProviders />});

await act(async () => {});

expect(await screen.findByText('Hello')).toBeTruthy();

I have no idea why but this seems to work. Could anyone help me understand why this works, or if there is a better way of doing this - as it feels a bit hacky. Thanks.

EDIT: Just remembered, the data loading function called by the provider is async - and once the data resolves it sets state, which is what is seemingly triggering the act warning.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions