title: How to make cy.visit() wait for ajax requests to complete?
body: <p>I would like to use <code>Cypress.Commands.overwrite()</code> to make the <code>cy.visit()</code> method do what it normally does and then wait until a loader element is no longer in the DOM, indicating that AJAX requests have completed. My goal is exactly this instead of creating a new command. The reason is to avoid situations where, e.g., someone might unknowingly use the unmodified <code>cy.visit()</code> and then assert that some elements not exist, when they possibly could exist and just not have loaded yet.</p>
  
  <p>While overwriting the default command, I appear to be running into problems with Cypress' use of promises. From the manual, it is clear how to overwrite <code>cy.visit()</code> when one wants to do stuff before calling the original function. However, I am unable to find an example, where the original function is called first and custom stuff happens only after that.</p>
  
  <p>So what I would like to do with the <code>overwrite()</code> command is this:</p>
  
  <pre><code>Cypress.Commands.add('visitAndWait', (url) =&gt; {
    cy.visit(url);
    cy.get('[data-cy="loader"]').should('not.exist');
  });
  </code></pre>
  
  <p>I have tested and can confirm that the above does what I need it to. Here are some attempts to make this work as an overwrite, all of which fail:</p>
  
  <pre><code>Cypress.Commands.overwrite('visit', (originalFn, url, options) =&gt; {
    return originalFn(url, options).then(() =&gt; cy.get('[data-cy="loader"]').should('not.exist'));
  });
  
  Cypress.Commands.overwrite('visit', async (originalFn, url, options) =&gt; {
    const res = await originalFn(url, options);
    await cy.get('[data-cy="loader"]').should('not.exist');
    return res;
  });
  </code></pre>
  
  <p>Both fail with this:</p>
  
  <p><a href="https://i.stack.imgur.com/bZ5Fy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bZ5Fy.png" alt="Error message for first two snippets."></a></p>
  
  <pre><code>Cypress.Commands.overwrite('visit', (originalFn, url, options) =&gt; {
    originalFn(url, options);
    return cy.get('[data-cy="loader"]').should('not.exist');
  });
  </code></pre>
  
  <p>And the last one fails with this:</p>
  
  <p><a href="https://i.stack.imgur.com/ry34l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ry34l.png" alt="Error message for the last snippet."></a></p>
  
  <p>Is this kind of an overwrite possible at all in Cypress, and if so, how is it done? Thank you!</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>The test code which causes the error in the last case is here:</p>
  
  <pre><code>cy.visit('/');
  cy.get('[data-cy="switch-to-staff"]').click();
  </code></pre>
  
  <p>Basically it tests a user role mocking panel by clicking a button that should mock a staff role.</p>