'How to resolve act() in useEffect?

I have a small problem with act() error in react-testing-library. In useEffect I try to call an function that is a promise. Promise returns some data and displays it, but even if the tests pass, the act error is still displayed. Component:

export function getUser() {
  return Promise.resolve({ name: "Json" });
}

const Foo = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const loadUser = async () => {
      const userData = await getUser();
      setUser(userData);
    };
    loadUser();
  }, []);

  return (
    <div>
      <p>foo</p>
      {user ? <p>User is: {user.name}</p> : <p>nothing</p>}
    </div>
  );
};

Also I have my Foo component inside of App Component, like that:

import Foo from "./components/Foo";

function App() {
  return (
    <div>
      some value
      <Foo />
    </div>
  );
}

export default App;

TEST:

  test("should display userName", async () => {
    render(<Foo />);
    expect(screen.queryByText(/User is:/i)).toBeNull();
    expect(await screen.findByText(/User is: JSON/i)).toBeInTheDocument();
  });

Do You have any ideas to resolve it?

EDIT: here's an error message

console.error
    Warning: An update to Foo inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */


Solution 1:[1]

Instead of act use waitFor to let the rendering resolve.

import { render, waitFor } from '@testing-library/react-native';
import { useEffect, useState } from 'react';
import { Text } from 'react-native';

describe('useState', () => {
  it('useState', () => {
    function MyComponent() {
      const [foo] = useState('foo');
      return <Text testID="asdf">{foo}</Text>;
    }
    const { getByTestId } = render(<MyComponent></MyComponent>)
    expect(getByTestId("asdf").props.children).toBe("foo");
  });
  it('useState called async', async () => {
    function MyComponent() {
      const [foo, setFoo] = useState('foo');
      useEffect(() => {
        (async () => {
          setFoo(await Promise.resolve('bar'))
        })()
      }, []);
      return <Text testID="asdf">{foo}</Text>;
    }
    const {getByTestId} = await waitFor(()=>render(<MyComponent></MyComponent>))
    expect(getByTestId("asdf").props.children).toBe("bar");
  });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Archimedes Trajano