In this article, we will look in detail at how we can implement recursion in cypress. Let’s further deep dive and automate a test case –
1. Go to https://alapanme.github.io/random-number.html. This web page generates a random number between 1 and 6 with every page refresh.
2. Using recursion assert the number ‘3’.
Step 1: Install the cypress-recurse node package.
1 | npm i -D cypress-recurse |
Step 2: Once installed, it should be reflected in your package.json file.
Step 3: Next, Let’s write a simple test script for our test case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import { recurse } from 'cypress-recurse' describe('Example to demonstrate recursion in Cypress', () => { it('Validate the number 3 using recursion', function () { cy.visit('https://alapanme.github.io/random-number.html') recurse( () => { cy.reload() return cy.get('#myNumber').invoke('text').then(parseInt) }, (x) => x === 3, { log: false, timeout: 7000, // try up to 7 seconds limit: 20, // try up to 20 times delay: 50 // delay before next iteration, ms } ).should('equal', 3) }) }) |
In the above test, first, we are importing cypress-recurse. Then, using cy.visit() we are accessing the webpage. Inside the recurse function we are first writing cy.reload() which will refresh the page at the start of each iteration and then using cy.get(‘#myNumber’).invoke(‘text’).then(parseInt) we are getting the number from the webpage and then converting it into an integer. Then, using (x) => x === 3 we are writing a condition that will continue the recursion until we get the number 3. Now, cypress-recurse provides us with 4 options:
a) log: false – With this you can add logs to your tests. You can pass ‘true’ or ‘false’ to print/not print default logs or you can also add a custom message like log: Custom Msg Finally found 3!!!.
With log: true you can see a lot of details like the number found for that iteration, attempts remaining, and also time remaining.
With log: ‘Custom Msg Finally found 3!!!’ no logs are printed for iterations. The custom message is logged when we have found our number.
b) With timeout: 7000 you can specify the time in ms until which the recursion should continue to take place. The default value for timeout is 4000 ms or 4 seconds.
c) With limit: 20 You can specify the maximum no. of recursions that you want. The default value for limit is 30. In case if the timeout is reached before completing the number of limits, the test will terminate and the remaining limits will be ignored.
d) With delay: 50 you can add the time between each iteration in ms.
Finally, once we have found the number using .should(‘equal’, 3) we are asserting it.
Step 4: After execution, we should see a ‘PASS’.
Do check out 🙂
Github:Â https://github.com/alapanme/Cypress-Automation
All Cypress Articles: https://testersdock.com/cypress-tutorial/
Awesome!! Thank You So much 🙂