3

In my e2e tests it happens that I have to wait for a xhr request to finish. So I have created an alias "graphql":

cy.server();
cy.route({
    method: "POST",
    url: Cypress.env('GRAPHQL_API'),
}).as("graphql");

It just listens to all POST requests, which is fine. I use it like this:

cy.wait("@graphql");

The problem is, I need to redeclare this alias not only in every test file but also in every single test! There must be a way to globally define this alias but I cannot find it.

  • Have you tried using it inside a before all hook? – PDHide Jan 26 at 1:05
1

You could try using it in a hook:

beforeEach(function () {
  cy.server();
cy.route({
    method: "POST",
    url: Cypress.env('GRAPHQL_API'),
}).as("graphql");
})

it('test', function () {
  cy.wait("@graphql");
})

Note that, alias works only with beforeEach and not before all, as alias will be cleared after each spec (means each 'it' block) .

https://github.com/cypress-io/cypress/issues/665

| improve this answer | |
0

There is no real way to have a global alias for network requests; cy.server only persists until the next test.

Depending on how your application behavior, you can create an helper function in your index.js and then call it for each needed test.

export const globalXHRpost = () => {
    cy.server()
    cy.route({
       method: "POST",
       url: Cypress.env('GRAPHQL_API')
       })
      .as("graphql")
    cy.visit('URL') //or whichever action initiates XHR
    cy.wait("@graphql")
}

You might consider restructuring your tests to have the alias cover XHR more than once.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.