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.
Can anyone suggest me how to wait dynamically until the request is resolved?
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')
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.
Based on your code, there are no assertions around logging in. You should avoid logging via UI if you do not plan on testing that area and instead log in using cy.request(), which will be dependent on how your app login was designed. Then you will be able to login via request and cy.visit() any page as a logged in user.