This code waits for a response and does things once it arrives.
How can I do stuff when wait times out?
cy.wait('@login').then((interception) => {
const token = interception.response.body.token
Cypress.env('ACCESS_CODE', token)
});
2
Answers
Achieving this isn’t possible in Cypress without a little maneuvering to get around the fact that
cy.wait()
doesn’t really support conditional results.But, we can use an undocumented feature of
cy.get()
to get all aliased calls and check the length of that yielded array to determine our actions:However,
cy.get('@alias.all')
does not have any waiting or retry mechanism, so if the call is triggered but not completed before callingcy.get()
, the call may not appear in the yielded array.If that is the case, we can swallow the Cypress error.
Two important things:
cy.on()
instead ofCypress.on()
will limit the changing of the event to only a specific test. If you’d like to implement this across your test suite, you’d want to do it in your support file and useCypress.on()
.return false
/throw err
-> include these so that your test won’t fail for the specified failure but will fail for unexpected failures.Now, given all of the above, I’d highly recommend not doing either of these. They are possible, but the ideal solution is to write your test or app in a way that is determinant and reproducible. (In an ideal test,) There shouldn’t be uncertainty about if a call is made or not. If this is reaching out to a third party resource, I’d maybe recommend stubbing or mocking out the entire flow to eliminate this ambiguity, and have other focused tests on the integration between the third party and your app.
There is no
.catch()
tocy.wait('@alias')
, but you can use this example Request-Polling with some modifications.In the following example
cy.catchAlias()
polls the intercept instead ofcy.wait('@alias')
.I have two intercepts in the test, but only the first one is triggered.
The "failed" intercept returns
null
instead of failing the test, and you can test the returned value to perform your on-fail actions.cypress-wait-if-happens
Gleb Bahmutov has a plugin cypress-wait-if-happens to do the same thing, with more options.