Allow cy.wait to fail

After reading a lot of docs and try to find a solution to my problem I didn't find anything, so here we go.

I have the following problem testing my end to end flow, the flow I'm testing does launch requests continuously but in one case I expect these requests to stop. In other words, I want to throw an error if the request is made and continue with errors when hits the timeout without any request.

cy.wait('@my-request', { timeout: 20000 })

I expect this to timeout if the app works fine so I tried to do this.

cy.wait('@my-request', { timeout: 20000 })
    .its('status').should('not.eq', 404)
    .its('status').should('not.eq', 200);

I expected to execute the chained tasks but this only happens when the request is made, as well as tried to use a .then but I have the same problem.

Upvotes: 3

Views: 3587

Answers (1)

Adding a global on fail event can help us but also limits to not execute additional code when this test is failing and we force it to be marked as done.

In the test definition we can add the done callback like in the example.

it('Description', (done) => {
// other test stuff
cy.on('fail', (err) => {
    if (err.name === 'CypressError' && err.message.includes('routeAlias') && err.message.includes('Timed out')) {
        done();
        return true;
    }
    throw err;
});
cy.wait('@routeAlias', { timeout: 20000 })
    .then(() => {
        throw new Error('Error request found.');
    });
});
// Any remaining code won't be executed if you need to reset something you need to create a new step, like in my case I did a new step to click a cancel button and prepare the app for the next test.

Now our test passes when this specific error is caught but any other error will lead to a test error.

This kind of workarounds are not recommended by cypress but unless cypress adds a catch to manage some errors it's the only way to fix my problem.

Upvotes: 2

Related Questions