How to have a global alias for network requests in Cypress



  • 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.



  • 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


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2