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

389
Visualizações
Mocking React Query useQueryClient to test cached data

I use a custom hook to share an increment function accross my app (it increments quantities in a shopping cart).

What that function does :

  • gets a data object from a React Query cache
  • increments the data quantity property
  • makes some API call via React Query useMutation then, on success, updates the React Query cache

After that, the components reads the React Query cart cache and updates the UI with the new quantity.

The hook does the job and finally the cache is updated as expected.

Now, I try to test the hook in a component to check that the UI is updated accordingly.

The API call is mocked using msw. Its returned value is used to update the cache :

  rest.put(`${api}/carts/1`, (req, res, ctx) => {
    return res(ctx.json({ data: [{ id: 1, quantity: 2 }] }));
  })

I also mocked the react-query queryClient.setQueryData and getQueryData functions so I can test their returns values.

jest.mock("react-query", () => ({
  ...jest.requireActual("react-query"),
  useQueryClient: () => ({
    setQueryData: jest.fn(),
    getQueryData: jest
      .fn()
      .mockReturnValueOnce({ data: [{ id: 1, quantity: 1 }] })
      .mockReturnValueOnce({ data: [{ id: 1, quantity: 2 }] }),
  }),
}));

Finally, I test the UI that should updates with the new quantity, but the mocked getQueryData always return the original quantity: 1, even with multiple call.

Now I'm not sure I have the right approach for that test.

about 4 years ago · Juan Pablo Isaza
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