Home > Mobile >  While running cypress test, when I visit new url after login, page stays on current url only
While running cypress test, when I visit new url after login, page stays on current url only

Time:01-15

Here is my code to perform login and then visit users.

        cy.visit('http://localhost:3000/')
        cy.get("#username").clear().invoke('val', "admin")
        cy.get("#password").clear().invoke('val',"password")
        cy.get("button[type='submit']").click()
        //cy.wait(500)-> If I un-comment this line, it works fine 
        cy.visit('/users/new')

Now it happens so fast that if I don't put wait of 500ms in between, it gives me an error of "failed xhr request". See the screenshot below.

enter image description here

Can anyone suggest me how to wait dynamically until the request is resolved?

CodePudding user response:

When you are logged in to your webpage, identify an element, and add an assertion that the element is visible after clicking the submit button.

cy.visit('http://localhost:3000/')
cy.get('#username').clear().invoke('val', 'admin')
cy.get('#password').clear().invoke('val', 'password')
cy.get("button[type='submit']").click()
cy.get('element after login').should('be.visible')

In case it takes more than 4 seconds for the after login screen to appear you can add custom timeouts as well.

cy.get('element after login', {timeout: 5000}).should('be.visible')

Also, Please avoid using cy.wait(500) as it will introduce test flakiness.

CodePudding user response:

Alapan's answer will work, but if you know what the login request looks like, you can always just intercept that and then chain your visit off of the intercept.

cy.intercept('your/login/request/url').as('login'); // modify intercept matcher to match your actual login request
cy.visit('http://localhost:3000/')
cy.get("#username").clear().invoke('val', "admin")
cy.get("#password").clear().invoke('val',"password")
cy.get("button[type='submit']").click().wait('@login').visit('/users/new')
  •  Tags:  
  • Related