How to access the React Query `queryClient` outside the provider? e.g. to invalidate queries in Cypress tests

Viewed 2537

Is it possible to access my app's React Query queryClient outside React?

In my some of my Cypress tests I fetch or mutate some data but then I'd like to invalidate all/part of the queryClient cache afterwards.

Is that possible?

I have tried importing the "same" queryClient that is used in the app, but it doesn't work.

ℹ️ I include these fetch/mutations in my tests merely to allow me to bypass convoluted steps that user's would normally take in the app which already have Cypress tests.

2 Answers

You can add a reference to queryClient to window, then invoke it's methods in the test.

From @АлексейМартинкевич example code,

import { QueryClient } from "react-query";

const queryClient = new QueryClient();

if (window.Cypress) {           // only during testing
  window.queryClient = queryClient;
}

export queryClient;

In the test

cy.window().then(win => {  // get the window used by app (window in above code)

  win.queryClient.invalidateQueries(...)  // exact same instance as app is using

})

I believe that importing will give you a new instance, you must pass a reference to the app's active instance.


Just read your comment which says exactly this - leaving answer as a code example.

You can store query client as a separate module/global variable. demo

Related