Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda