Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

91
Vistas
React `act` warning on DidMount and Promise

Okay so I have this bunch of code that's is thrown on useEffect(() => {...}, []) a.k.a componentDidMount.

// utils/apiCalls.ts

export const loadData = async <T>(
  url: string,
  errorMsg = "Couldn't retrieve data.",
): Promise<T> => {
  const res = await fetch(url, { mode: 'cors', credentials: 'include' });
  if (res.ok) return await res.json();
  throw new Error(errorMsg);
};

export const loadChat = (id: number): Promise<IChat> => {
  return loadData<IChat>(
    `${CHAT_API}/${id}/nested/`,
    "We couldn't get the chat.",
  );
};
// components/MessageContainer.tsx

const MessageContainer = (/* props */) => {
  /*
   * Some coding...
   */

  useEffect(() => {
  if (session === null) return;
  if (chat === null) {
    loadChat(session.chat).then(setChat).catch(alert);
    return;
  }
  // More coding...
}, [session, chat]);
};

The problem comes when I try to test it with @testing-library/react since it gives me this warning Warning: An update to MessagesContainer inside a test was not wrapped in act(...).

How can I make a correct test for this? Here's the test I have right now.

// tests/MessagesContainer.spec.tsx

describe('MessagesContainer suite', () => {
  it('loads messages on mount', () => {
    fetchMock.mockResponseOnce(JSON.stringify(ChatMock));
    render(
      <SessionContext.Provider value={SessionMock}>
        <MessagesContainer {...MessagesContainerMockedProps} />
      </SessionContext.Provider>,
    );

    expect(fetchMock.mock.calls.length).toEqual(1);
  });
});

NOTE: Wrapping render on act did not work.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

So at the end I used waitFor in order to check if element has been mounted.

// tests/ChatMessagesContainer.spec.tsx

describe('ChatMessagesContainer suite', () => {
  it('renders multiple messages', async () => {
    const messageMock = Object.assign({}, MessageMock);
    messageMock.message = faker.lorem.words();
    const chatMock = Object.assign({}, ChatMock);
    chatMock.chat_message_set = [MessageMock, messageMock];
    fetchMock.mockResponseOnce(JSON.stringify(chatMock));
    const { getAllByText } = render(
      <AuthContext.Provider value={UserMock}>
        <SessionContext.Provider value={SessionMock}>
          <MessagesContainer {...MessagesContainerMockedProps} />
        </SessionContext.Provider>
      </AuthContext.Provider>,
    );

    // THIS IS THE IMPORTANT PART
    expect(await screen.findByText(MessageMock.message)).toBeInTheDocument();
    expect(getAllByText(MessageMock.author.username).length).toEqual(2);
  });
});

This article was really useful Maybe you don't need act.

about 4 years ago · Juan Pablo Isaza Denunciar

0

fetch is async function which finished only all regular script execution ends. You need to really await fetch finished before call expect. Moreover, it is not recommend to use testing-library as you did. You want to check how element rendered after fetch, write you test accordance to exception result in UI. For instance, if after fetching you expect something like this:

<span>message</span>

you expect span with message, and test will be:

expect(screen.findByText('message'));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda