There is a plugin that is cool enough to re-run cypress commands until the specified function returns true. Recurse is the plugin used and is also a way to loop through some cypress commands.
Table of Content
1. Install Cypress Recurse Plugin
Let us install the plugin first.
npm i -D cypress-recurse
Ok, then it has been installed. Just import the plugin in the commands.js and e2e.js inside the support folder.
Example
- Let us see how the recurse works in real-time.
- Here is what we are going to do.
- This is a page with a number that randomly generates numbers when we reload.
- Let us try to reload the page until the number "7" appears using recurse looping.
describe('Automate AutoPract',()=>{
it('Recurse',()=>{
cy.visit('./randomnumber.html')
recurse(
function () {
return cy.get('#result').invoke('text').then(parseInt)
},
function (n) {
return n === 7
},
{
limit: 60,
delay: 1000, // sleep for 1 second before reloading the page
timeout: 60_000, // try up to one minute
log: false,
post () {
cy.reload()
}
})
})
})
- First, using the recurse command, we are writing the function and passing in the locator for the number element on the page.
- In the second function, we are fetching the jquery argument of the first function and naming it "n."
- This n contains the locator of the number from the previous function.
- We are specifying that n should be equal to 7.
- This is the condition part we have done up to now.
- In the next, we are using some options of recursing. Let's see what it does in detail.
Limit: Number of retries the recurse needs to perform. Without this, it fails within 4-5 retries.
Delay: Sleep time before reloading the next page.
Timeout: retries up to the specified time.
Log: To log in to the test command DOM.
Post: The actions we need to repeat have to be mentioned within the post. In this case, we want to repeat reload until number 7.
Let us run and check.
- So we can see that it reloaded up to a point and stopped when 7 appeared.
Now let us assert the numbers which are not 7 and push them into an array.
it('Recurse',()=>{
cy.visit('./randomnumber.html')
recurse(
function () {
return cy.get('#result').invoke('text').then(parseInt)
},
function (n) {
return n === 7
},
{
limit: 60,
delay: 1000, // sleep for 1 second before reloading the page
timeout: 60_000, // try up to one minute
log: false,
reduceFrom: [],
reduce(numbers, n) {
numbers.push(n)
},
post () {
cy.reload()
},
yield: 'reduced,'
},
).then(function (numbers) {
expect(numbers).to.not.include(7)
})
})
})
- Using the reduceFrom, we pushed results from "n" into "numbers."
- We used yield then to make recurse yield the looped and ignored numbers.
- Using the "then," we pass the numbers and expect to assert it not to include 7.
- And from the output, we can see all the numbers which asserted that it does not include 7.
- Log in to post comments