cypress-recurse icon indicating copy to clipboard operation
cypress-recurse copied to clipboard

A way to re-run Cypress commands until a predicate function returns true

cypress-recurse

ci status renovate-app badge cypress version 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 the reduce 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 with value and reduced 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

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)

Debug logs

Blog post

Read Writing Cypress Recurse Function

Videos

I have explained how this module was written in the following videos

  1. Call cy task until it returns an expected value
  2. Reusable recursive function
  3. Reusable function with attempts limit
  4. Recursion function with time limit
  5. Convert recurse to use options object
  6. Add JSDoc types to the options parameter
  7. Published cypress-recurse NPM package

Bonus videos

  1. use cypress-recurse to find the downloaded file
  2. canvas visual testing
  3. wait for API to respond
  4. get to the last page by clicking the "Next" button
  5. Use cypress-recurse To Scroll The Page Until It Loads The Text We Are Looking For
  6. Use cypress-recurse Plugin To Confirm The Table Gets Sorted Eventually
  7. Use cypress-recurse To Ping The Site Before Visiting It
  8. Use cypress-recurse To Click The Back Button Until It No Longer Exists
  9. Reload The Page Until We See 7 Plus Check The Numbers Before That
  10. Click On The Button Until It Becomes Disabled
  11. Stub cy.request Command Using cy.stub And Use cypress-recurse Example
  12. Use cypress-recurse To Open Accordion Panels Until It Finds A Button To Click
  13. 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.