I'm using Cypress for its component tests. These are integration-style tests, I mount my whole app (React) and then click through it. All API calls are mocked using the Cypress Intercept feature. So far this has been an incredibly powerful solution, far more robust than any other FE testing suite I've worked with.
One limitation I've run into is with the intercepted API calls. I've got this scenario where I've got an API that is called twice during the flow of a given test. One of the conditions I want to validate is that it is, indeed, called twice, as the second call is triggered by the logic I am testing.
So the specific Cypress validation I want to work is this:
cy.get('#myButton').click(); // Triggers the second API call
cy.get('@myApi.all').should('have.length', 2);
Now, the problem is that the above code, on its own, fails because Cypress only registers a single call to the intercepted API named myApi
. The reason for this is Cypress moves to immediately validate the number of calls to this intercepted API, rather than waiting for the action I just triggered in the UI.
The only way I know of to make the above code work is to add in explicit waiting, like this:
cy.get('#myButton').click(); // Triggers the second API call
cy.wait(300);
cy.get('@myApi.all').should('have.length', 2);
Because I am explicitly waiting 300ms after clicking the button, enough time passes for the second API call to occur and Cypress to register it, so the test passes.
I don't like this solution. I don't like adding explicit waits to my test code, it feels like a band-aid and will likely be error prone as it relies on execution timing to succeed. However, I simply do not know of a better option.