Upgrading to v4/v5 has broken cypress tests that uses `cy.clock` #6171
Send to my agentDescribe the bug#
We have many cypress tests that uses cy.clock to be able to control browser's timing. We were using react-query V3 and everything was working as expected without issues.
After upgrading to v4 all the tests that uses cy.clock are broken. Upgrading to V5 doesn't help either.
useQuery calls the given queryFn and request is successfully sent to api. However, component is not re-rendered and react query is stuck in loading state unless we explicitly wait for request in our e2e and call cy.tick(0) to trigger vm turn manually. This change makes writing e2e tests a nightmare, because there is many api calls and now we have to track every request just to trigger a vm turn.
Versions: react: 18.2.0 @tanstack/react-query: 5.0.0-rc.16 (same issue is with V4) cypress: 12.14.0
Adding the simplest code to demonstrate the issue:
index.tsx
import React from 'react';
import { IsolatedExample } from './IsolatedExample';
import { QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 20_000, gcTime: 20_000 } },
});
createRoot(document.getElementById('root')!).render(
<QueryClientProvider client={queryClient}>
<IsolatedExample />
</QueryClientProvider>
);
React component
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
export const IsolatedExample = () => {
const { data } = useQuery({
queryKey: ['isolated-example'],
queryFn: async () => {
const { data } = await axios.get('http://localhost:3000/api/v1/me');
return data;
},
});
return (
<div>
Email: <span data-testid="user-email">{data?.email || 'no-email'}</span>
</div>
);
};
Cypress test:
describe('isolated example', () => {
it('should demonstrate the effort needed for react query to work', () => {
cy.clock(new Date()); // Mocking all the brower's timing api - Date, setTimeout, setInterval
cy.intercept('GET', 'http://localhost:3000/api/v1/me').as('getUser'); // Intercepting calls to http://localhost:3000/api/v1/me and assigning alias
cy.visit('http://localhost:3000'); // Opening our page to demonstrate the issue
// These two lines are the main problem - we have to know where to put 'wait' in order to wait for request to happen
cy.wait('@getUser'); // Wait for request to http://localhost:3000/api/v1/me
cy.tick(0); // Trigger new vm turn for react query to re-render component with new data
cy.findByTestId('user-email').should('contain', 'test@test.test'); // Test passes
});
it('should demonstrate how it was working before v4/v5 without zero effort', () => {
cy.clock(new Date()); // Mocking all the brower's timing api - Date, setTimeout, setInterval
cy.visit('http://localhost:3000'); // Opening our page to demonstrate the issue
cy.findByTestId('user-email').should('contain', 'test@test.test'); // Test fails, because even if data was fetched by react-query, but component was not re-rendered
});
});
Your minimal, reproducible example#
https://stackblitz.com/edit/react-ts-cypress-3ntyhr?file=cypress%2Fe2e%2Fisolated-example.spec.ts
Steps to reproduce#
- Write a simple component that uses
useQuery - Write a cypress test and add
cy.clock()to mock timing api - Run the test and see how your component is never re-rendered unless you intercept and wait for the request to api and call
cy.tick(0)to trigger new vm turn.
Expected behavior#
In order to use react-query with pleasure as it was before v4, component should re-render without waiting for the request to happen and calling cy.tick(0) afterwards. This upgrade impacts our work in a really bad way as we have many e2e tests and there will be much more of them. Tracking every request makes writing tests way more time consuming.
How often does this bug happen?#
None
Screenshots or Videos#
No response
Platform#
macOS, Chrome 118.0.5993.70 (though it shouldn't matter as this issue happens everywhere)
Tanstack Query adapter#
None
TanStack Query version#
5.0.0-rc.16
TypeScript version#
5.1.6
Additional context#
No response
TkDodo closed this
TkDodo added labelsduplicate
sounds like a duplicate of:
I see this issue is closed, but what is the solution? It is suggested to mock only those functions which are actually needed to mock (e.g. mock only
setTimeoutand leave everything else). And it helps only in some cases. We have used react-query v3 for a long time and it was amazing - easy to use, simple to learn, feature-rich, works without any issues. Upgrading to v4/v5 was really disappointing and the main disappointment is that writing tests is much, much harder now because of the simple reason - you have to trigger new vm turn manually, when react query loads data in order for component to be re-rendered. And we see this as a major drawback of the library as the tests and mocking time is an inevitable part of any bigger project. For now the 'best' solution looks to downgrade react-query to V3 and use it until it is possible to use it without keeping other dependencies outdated (e.g. until it is not supported by the new version of react). And then look for an alternative which doesn't complicate writing tests.Our internal task scheduling uses
setTimeoutfor all cases since v4.v3:
export function scheduleMicrotask(callback: () => void): void { Promise.resolve() .then(callback) .catch(error => setTimeout(() => { throw error }) ) }v4:
export function scheduleMicrotask(callback: () => void) { sleep(0).then(callback) }this makes sure we can batch more updates together that come in short succession to avoid additional, unnecessary in-between re-renders.
cy.tick(0); // Trigger new vm turn for react query to re-render component with new data
I'm not sure what this code is supposed to be doing. Seems you are relying on the fact that advancing the clock by 0ms will trigger a re-render? This doesn't seem like an idiomatic good approach to testing components. cypress is async per default and will just wait for and retry things anyways, so you can just do:
it('should demonstrate the effort needed for react query to work', () => { cy.intercept('GET', 'http://localhost:3000/api/v1/me').as('getUser'); cy.visit('http://localhost:3000'); cy.wait('@getUser'); cy.findByTestId('user-email').should('contain', 'test@test.test'); });and it should just work.
Upgrading to v4/v5 was really disappointing and the main disappointment is that writing tests is much, much harder now because of the simple reason - you have to trigger new vm turn manually, when react query loads data in order for component to be re-rendered
again, you don't need to "trigger" anything. I think you're approaching cypress test from a position that's a bit too low-level. Not here to give advice on how to write tests, but generally, it should be done to mimic what the user does in the application. The user doesn't know or care about "vm turns" and mocked timers, and neither should your tests.
If this worked in v3 then great, you've been relying on an implementation detail that happened to change in v4. But don't blame the library for your choices of writing tests that imo are a bit weird regardless of that.
We are using e2e tests to mimic what the user does and using unit tests for low level things. The problem is that sometimes we need to e2e test long running operations.
Example scenario: User clicked a button, request has been sent to BE, then UI starts polling BE and waits for some specific response to be returned. UI is in specific state while polling happens and user is restricted from doing some actions until BE returns specific response. Once expected response was returned, UI state changes, user is allowed to do more actions and polling ends. How is that too low level for e2e?
For such scenarios we need to mock the timing API (using
cy.clock, which was designed for such cases). Because we have many time-dependent tests, e2e would run in pipeline forever without mocking a timing API. The code snippet you have posted works if we don't usecy.clock. Previously it was working withcy.clocktoo. It is good that you want to save extra re-renders, but keep in mind that other thing got broken - mocking a timing API. When you are building a library which are used by millions, it's just impossible to fulfill everybody's needs without complicating things for others so I don't blame anybody. If you could at least removesetTimoutbetweenqueryFnreturning a response and component being re-rendered that would solve many problems. Thanks for a good tool anyway!I don't understand why such a scenario would need time mocking:
- you click a button, it makes a request
- you assert that the ui is in the given loading state
- you wait for the polling request to be made
- you make the polling request return a response that is interpreted as "finished"
- you assert the final ui state
where in this list do you need time mocking ?
I don't understand why such a scenario would need time mocking:
you click a button, it makes a request
you assert that the ui is in the given loading state
you wait for the polling request to be made
- you make the polling request return a response that is interpreted as "finished"
you assert the final ui state
where in this list do you need time mocking ?
This is happy path - when expected request was returned in a given time, which is several minutes. And for that we don't even use
cy.clockbecause time mocking is not needed. To test cases when expected request wasn't returned in a given time we usecy.clock. ExcludedsetTimeoutfrom mocked timing API functions and tests passes, so for now problem is solved.Using v4, we were really testing the interval the hook was using (so first giving it response A, then after the interval B and see if the container did its work). All we had to do is use the second argument of cy.clock(), so in our case
['setInterval']In my example, before the test being executed:
cy.clock(new Date(2023, 1, 1, 12, 0, 0), ['setInterval'])then in test itself:
cy.tick(10 * 60_000 + 1000) cy.wait('@version').its('response.statusCode').should('eq', 200)I wish it was that easy with Jest as well, in jest its painfull :)
Sign in to join this conversation.
sounds like a duplicate of: