I am using the following code in cypress version 12 on mac OS.
The issue with my test is that it is only running for the first time when the session is running the setup()
function, but when I re-run the same test and the session is restored the test does not got executed. (cypress is unable to find the element).
Cypress error:-
Timed out retrying after 6000ms: Expected to find element: :nth-child(1) > .link-button, but never found it.
What I have tried so far:- Custom command for login:-
Cypress.Commands.add('login', (login_email, login_password)=>{
cy.session('loginSession', ()=>{
cy.visit('https://www.telerik.com/')
cy.get('#onetrust-accept-btn-handler').click()
cy.get('#js-tlrk-nav-drawer-button').click()
cy.get('#js-tlrk-nav-not-auth-container > .TK-Aside-Menu-Button').click()
cy.get('#email').type(login_email)
cy.get('.btn').click()
cy.get('#password').type(login_password)
cy.get('.btn').click()
})
})
spec file code:-
describe('Account page', ()=>{
beforeEach(()=>{
cy.login('youremail@gmail.com', 'somepassword')
})
it('update profile', ()=>{
cy.get(':nth-child(1) > .link-button').click()
})
})
I have also used { testIsolation: false }
in my cypress.config.js file
It's hard to be definitive about this case, but I would try adding an explicit visit inside the test itself.
When the session command runs for the first time, you are hitting the login sequence which results in navigation after login to the home page (the one containing the element that fails on the second try).
But AFIK on the 2nd call cy.session()
only restores the login credentials, but does not perform the "manual" login steps and therefore does not invoke a redirect.
You can get a feel for the process described here Where to call cy.visit()
beforeEach(() => {
cy.login('email@gmail.com', 'password')
})
it('update profile', () => {
cy.visit('https://www.somewebsite.com/') // presume this is the target page
cy.get(':nth-child(1) > .link-button').click()
})
Also, you can leave testIsolation:true
when using cy.session()
, theoretically at least.
Validation function
Another tool in the toolbox is the validation function.
This checks to see if the result of cache restoration (on the 2nd call) is valid. If not it re-runs the setup()
function.
In your case, that failing element query could be used.
Cypress.Commands.add('login', (login_email, login_password) => {
cy.session('loginSession', () => {
cy.visit('https://www.somewebsite.com/')
cy.get('#js-tlrk-nav-not-auth-container > .TK-Aside-Menu-Button')
.click()
cy.get('#email').type(login_email)
cy.get('.btn').click()
cy.get('#password').type(login_password)
cy.get('.btn').click()
},
{
validate() {
cy.get(':nth-child(1) > .link-button').should('exist')
}
})
})