Reputation: 1649
I'm trying to write a test but I've got to a point where I need to wait for some text to become visible.
Basically up to this point I have uploaded a file and then navigated to another page, this new page just says "Processing.." when the file is finished being checked it will say "Success!"
The problem is this page isn't calling an API every x seconds to update the text it just does it once on a page load so I want to check if the page says "Processing.." call cy.reload() check again, call cy.wait(1000) reload and check again etc until the page says "Success!".
My issue is how do I check if text is present without it being an assert and failing the test?
Upvotes: 5
Views: 9471
Reputation: 1040
I had the same issue and authored the following based on other answers in SO (nobody had quite what I wanted).
Add this to commands.js
to make it available to all tests.
Cypress.Commands.add('reloadUntilFound', (url, selector, retries=3, retry_wait=1000) => {
if(retries==0){
throw `exhausted retries looking for ${selector} on ${url}`
}
cy.visit(url)
cy.get('body').then(body => {
let msg = `url:${url} selector:${selector} retries:${retries}`
if (body.find(selector).length===1) {
console.log(`found ${msg}`)
}else{
console.log(`NOT found ${msg}`)
cy.wait(retry_wait)
cy.reloadUntilFound(url, selector, retries - 1)
}
})
})
Invoke it as follows.
cy.reloadUntilFound('/transactions', 'td:contains($4.44)')
Upvotes: 3
Reputation:
This has been asked a few times, and the short answer is to use jQuery, e.g
cy.visit(...)
cy.wait(1000) // in case the page is initially slow to load
const text = Cypress.$('div').text();
if (text.trim().startsWith('Processing') {
cy.wait(1000)
cy.reload()
}
That gets you one reload, but I guess you want to repeat that until 'Success...', for which recursion seems to be the only way to repeat stuff until the right DOM appears.
function waitForText(attempt = 0) {
if (attempt > 100) { // choose cutoff point, must have this limiter
throw 'Failed'
}
cy.wait(1000);
const text = Cypress.$('div').text();
if (text.trim().startsWith('Processing') {
cy.reload();
waitForText(attempt + 1)
}
}
cy.visit(...)
waitForText()
Upvotes: 4