A small example showing how to use recursion to avoid JavaScript loops in Cypress
In the plugins file we have a task that returns a random digit after 1 second delay. We want to call cy.task
until it returns 7. See several solutions in the cypress/integration/spec.js file.
I have made this code into a reusable function, available on NPM under cypress-recurse
. See the repository bahmutov/cypress-recurse.
I have explained the solution to this problem and refactored it several times to add more features, see the following videos
- Call cy task until it returns an expected value
- Reusable recursive function
- Reusable function with attempts limit
- Recursion function with time limit
- Convert recurse to use options object
- Add JSDoc types to the options parameter
- The recipe "Page reloads" reloads the page until it shows the number 7