cypress-recurse
cypress-recurse copied to clipboard
A way to re-run Cypress commands until a predicate function returns true
cypress-recurse
A way to re-run Cypress commands until a predicate function returns true
Jump to: Options, Examples, Debugging, Videos.
Install
npm i -D cypress-recurse
# or use Yarn
yarn add -D cypress-recurse
Use
import { recurse } from 'cypress-recurse'
it('gets 7', () => {
recurse(
() => cy.task('randomNumber'),
(n) => n === 7,
)
})
The predicate function should return a boolean OR use assertions to throw errors. If the predicate returns undefined, we assume it passes, see examples in expect-spec.js.
it('works for 4', () => {
recurse(
() => cy.wrap(4),
(x) => {
expect(x).to.equal(4)
},
).should('equal', 4)
})
Important: the commands inside the first function cannot fail - otherwise the entire test fails. Thus make them as "passive" as possible, and let the predicate function decide if the entire function needs to be retried or not.
Yields
The recurse
function yields the subject of the command function.
import { recurse } from 'cypress-recurse'
it('gets 7', () => {
recurse(
() => cy.wrap(7),
(n) => n === 7,
).should('equal', 7)
})
Options
it('gets 7 after 50 iterations or 30 seconds', () => {
recurse(
() => cy.task('randomNumber'),
(n) => n === 7,
{
log: true,
limit: 50, // max number of iterations
timeout: 30000, // time limit in ms
delay: 300, // delay before next iteration, ms
},
)
})
You can see the default options
import { RecurseDefaults } from 'cypress-recurse'
log
The log option can be a boolean flag or your own function. For example to pretty-print each number we could:
recurse(
() => {...},
(x) => x === 3,
{
log: (k) => cy.log(`k = **${k}**`),
}
)
You can simply print a given string at the successful end of the recursion
recurse(
() => {...},
(x) => x === 3,
{
log: 'got to 3!',
}
)
See the log-spec.js
post
If you want to run a few more Cypress commands after the predicate function that are not part of the initial command, use the post
option. For example, you can start intercepting the network requests after a few iterations:
// from the application's window ping a non-existent URL
const url = 'https://jsonplaceholder.cypress.io/fake-endpoint'
const checkApi = () => cy.window().invoke('fetch', url)
recurse(checkApi, ({ ok }) => ok, {
post: ({ limit, value }) => {
// after a few attempts
// stub the network call and respond
if (limit === 1) {
// start intercepting now
console.log('start intercepting')
return cy.intercept('GET', url, 'Hello!').as('hello')
}
// you can use the value prop to look at the fetch results
},
})
The argument is a single object with limit
, value
, reduced
, success
, and elapsed
properties.
See the post-spec.js and find-on-page/spec.js.
By default, the last value is NOT passed to the post
callback. You can pass the last value by setting an option
recurse(fn1, predicate, {
post () {
...
},
postLastValue: true
})
A good combination is postLastValue: true
and post({ value, success })
where the value
is yielded by the first function, and the success
is the result of checking that value using the predicate function.
Note: if you specify both the delay and the post
options, the delay runs first.
custom error message
Use the error
option if you want to add a custom error message when the recursion timed out or the iteration limit has reached the end.
recurse(
() => {...},
(x) => x === 3,
{
error: 'x never got to 3!',
}
)
accumulator
Similar to reducing an array, the reduce
function has an option to accumulate / reduce the values in the given object. The following options work together
-
reduceFrom
is the starting value, like[]
-
reduce(acc, item)
receives each value and the current accumulator value -
reduceLastValue
is false by default, turn it on to call the thereduce
function with the last value (for which the predicate function has returned true)
TODO: document the above options
If there is a reduced value, it will be passed as the second argument to the predicate function.
See the reduce-spec.js for examples.
yield
If you are accumulating a reduced value, you can yield it instead of the last value. You can even yield both the last and the reduced values.
-
yield: "value"
yields the value that passed the predicate function -
yield: "reduced"
yields the accumulated value -
yield: "both"
yields an object withvalue
andreduced
properties
See the reduce-spec.js for examples.
each
This plugin also includes the each
function that iterates over the given subject items. It can optionally stop when the separate predicate function returns true.
import { each } from 'cypress-recurse'
it('iterates until it finds the value 7', () => {
cy.get('li').then(
each(
$li => ..., // do something with the item
$li => $li.text() === '7' // stop if we see "7"
)
)
})
The each
function yields the original or transformed items
const numbers = [1, 2, 3, 4]
cy.wrap(numbers)
.then(
each(
(x) => {
return 10 + x
},
// stop when the value is 13
(x) => x === 13,
),
)
.should('deep.equal', [11, 12])
See the each-spec.js file.
Examples
- clear and type text into the input field until it has the expected value, see type-with-retries-spec.js, watch the video Avoid Flake When Typing Into The Input Elements Using cypress-recurse and read the blog post Solve Flake In Cypress Typing Into An Input Element
- avoid-while-loops-in-cypress repo
- monalego repo and Canvas Visual Testing with Retries blog post, watch the video
- reloading the page until it shows the expected text recipe
- pinging the API endpoint until it responds
- HTML canvas bar chart testing
- Browse Reveal.js Slides Using Cypress and cypress-recurse
- opening each accordion panel until we find a button to click accordion-spec.js, see video Use cypress-recurse To Open Accordion Panels Until It Finds A Button To Click
Debugging
Use options log: true
and debugLog: true
to print additional information to the Command Log
recurse(getTo(2), (x) => x === 2, {
timeout: 1000,
limit: 3,
delay: 100,
log: true,
debugLog: true,
}).should('equal', 2)
Blog post
Read Writing Cypress Recurse Function
Videos
I have explained how this module was written in 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
- Published cypress-recurse NPM package
Bonus videos
- use cypress-recurse to find the downloaded file
- canvas visual testing
- wait for API to respond
- get to the last page by clicking the "Next" button
- Use cypress-recurse To Scroll The Page Until It Loads The Text We Are Looking For
- Use cypress-recurse Plugin To Confirm The Table Gets Sorted Eventually
- Use cypress-recurse To Ping The Site Before Visiting It
- Use cypress-recurse To Click The Back Button Until It No Longer Exists
- Reload The Page Until We See 7 Plus Check The Numbers Before That
- Click On The Button Until It Becomes Disabled
- Stub cy.request Command Using cy.stub And Use cypress-recurse Example
- Use cypress-recurse To Open Accordion Panels Until It Finds A Button To Click
- Access The Response Text Yielded By The Plugin cypress-response
Small print
Author: Gleb Bahmutov <[email protected]> © 2021
License: MIT - do anything with the code, but don't blame me if it does not work.
Support: if you find any problems with this module, email / tweet / open issue on Github
MIT License
Copyright (c) 2020 Gleb Bahmutov <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.