Skip to content

bahmutov/cypress-map

Repository files navigation

cypress-map ci cypress version

Extra Cypress query commands for v12+

Install

Add this package as a dev dependency:

$ npm i -D cypress-map
# or using Yarn
$ yarn add -D cypress-map

Include this package in your spec or support file to use all custom query commands

import 'cypress-map'

Alternative: import only the query commands you need:

import 'cypress-map/commands/map'
import 'cypress-map/commands/tap'
// and so on, see the /commands folder

API

apply

const double = (n) => n * 2
cy.wrap(100).apply(double).should('equal', 200)

It works like cy.then but cy.apply(fn) is a query command. Function fn should be synchronous, pure function that only uses the subject argument and returns new value The function callback fn cannot use any Cypress commands cy.

You can pass additional left arguments to the callback function. Then it puts the subject as last argument before calling the function:

cy.wrap(8).apply(Cypress._.subtract, 4).should('equal', -4)

applyRight

Without arguments, cy.applyRight works the same as cy.apply. If you pass arguments, then the subject plus the arguments become the arguments to the callback. The subject is at the left (first) position

cy.wrap(8).applyRight(Cypress._.subtract, 4).should('equal', 4)
// same as
cy.wrap(8)
  .apply((subject) => Cypress._.subtract(subject, 4))
  .should('equal', 4)

partial

Sometimes you have the callback to apply, and you know the first argument(s), and just need to put the subject at the last position. This is where you can partially apply the known arguments to the given callback.

// the Cypress._.add takes to arguments (a, b)
// we know the first argument a = 5
// so we partially apply it and wait for the subject = b argument
cy.wrap(100).partial(Cypress._.add, 5).should('equal', 105)
// same as
cy.wrap(100)
  .apply((subject) => Cypress._.add(5, subject))
  .should('equal', 105)

applyToFirst

If the current subject is an array, or a jQuery object, you can apply the given callback with arguments to the first item or element. The current subject will be the last argument.

// cy.applyToFirst(callback, ...args)
cy.wrap(Cypress.$('<div>100</div><div>200</div>'))
  .applyToFirst((base, el) => parseInt(el.innerText, base), 10)
  .should('equal', 100)

applyToFirstRight

If the current subject is an array, or a jQuery object, you can apply the given callback with arguments to the first item or element. The current subject will be the first argument.

// cy.applyToFirstRight(callback, ...args)
cy.wrap(Cypress.$('<div>100</div><div>200</div>'))
  .applyToFirstRight((el, base) => parseInt(el.innerText, base), 10)
  .should('equal', 100)

invokeFirst

We often just need to call a method on the first element / item in the current subject

cy.get(selector).invokeFirst('getBoundingClientRect')
// compute the vertical center for example

map

Transforms every object in the given collection by running it through the given callback function. Can also map each object to its property. An object could be an array or a jQuery object.

// map elements by invoking a function
cy.wrap(['10', '20', '30']).map(Number) // [10, 20, 30]
// map elements by a property
cy.get('.matching')
  .map('innerText')
  .should('deep.equal', ['first', 'third', 'fourth'])

You can even map properties of an object by listing callbacks. For example, let's convert the age property from a string to a number

cy.wrap({
  age: '42',
  lucky: true,
})
  .map({
    age: Number,
  })
  .should('deep.equal', {
    age: 42,
    lucky: true,
  })

You can avoid any conversion to simply pick the list of properties from an object

const person = {
  name: 'Joe',
  age: 21,
  occupation: 'student',
}
cy.wrap(person).map(['name', 'age']).should('deep.equal', {
  name: 'Joe',
  age: 21,
})

You can extract nested paths by using "." in your property path

cy.wrap(people)
  .map('name.first')
  .should('deep.equal', ['Joe', 'Anna'])
// equivalent to
cy.wrap(people)
  .map('name')
  .map('first')
  .should('deep.equal', ['Joe', 'Anna'])

mapInvoke

cy.get('#items li')
  .find('.price')
  .map('innerText')
  .mapInvoke('replace', '$', '')
  .mapInvoke('trim')

reduce

cy.get('#items li')
  .find('.price')
  .map('innerText')
  .mapInvoke('replace', '$', '')
  .map(parseFloat)
  .reduce((max, n) => (n > max ? n : max))
// yields the highest price

You can provide the initial accumulator value

cy.wrap([1, 2, 3])
  .reduce((sum, n) => sum + n, 10)
  .should('equal', 16)

See reduce.cy.js

tap

cy.get('#items li')
  .find('.price')
  .map('innerText')
  .tap() // console.log by default
  .mapInvoke('replace', '$', '')
  .mapInvoke('trim')
  // console.info with extra label
  .tap(console.info, 'trimmed strings')

Notice: if the label is provided, the callback function is called with label and the subject.

make

A retryable query that calls the given constructor function using the new keyword and the current subject as argument.

cy.wrap('Jan 1, 2019')
  // same as "new Date('Jan 1, 2019')"
  .make(Date)
  .invoke('getFullYear')
  .should('equal', 2019)

print

A better cy.log: yields the value, intelligently stringifies values using % and string-format notation.

cy.wrap(42)
  .print() // "42"
  // and yields the value
  .should('equal', 42)
// pass formatting string
cy.wrap(42).print('the answer is %d') // "the answer is 42"
cy.wrap({ name: 'Joe' }).print('person %o') // 'person {"name":"Joe"}'
// use {0} with dot notation, supported deep properties
// https://github.com/davidchambers/string-format
cy.wrap({ name: 'Joe' }).print('person name {0.name}') // "person name Joe"
// print the length of an array
cy.wrap(arr).print('array length {0.length}') // "array length ..."
// pass your own function to return formatted string
cy.wrap(arr).print((a) => `array with ${a.length} items`)
// if you return a non-string, it will attempt to JSON.stringify it
cy.wrap(arr).print((list) => list[2]) // JSON.stringify(arr[2])

See print.cy.js for more examples

findOne

Finds a single item in the subject. Assumes subject is an array or a jQuery object. Uses Lodash _.find method.

// using predicate function
const isThree = n => n === 3
cy.wrap([...]).findOne(isThree).should('equal', 3)
// using partial known properties of an object
cy.wrap([...]).findOne({ name: 'Anna' }).should('have.property', 'name', 'Anna')

See find-one.cy.js

primo

cy.get('.matching')
  .map('innerText')
  .primo()
  .invoke('toUpperCase')
  .should('equal', 'FIRST')

See primo.cy.js

prop

Works like cy.its for objects, but gets the property for jQuery objects, which cy.its does not

cy.get('#items li.matching')
  .last()
  .prop('ariaLabel')
  .should('equal', 'four')

See prop.cy.js

update

Changes a single property inside the subject by running it through the given callback function. Useful to do type conversions, for example, let's convert the "age" property to a Number

cy.wrap({ age: '20' })
  .update('age', Number)
  .should('deep.equal', { age: 20 })

at

Returns a DOM element from jQuery object at position k. Returns an item from array at position k. For negative index, counts the items from the end.

cy.get('#items li').at(-1).its('innerText').should('equal', 'fifth')

See at.cy.js

sample

Returns a randomly picked item or element from the current subject

cy.get('#items li').sample().should('have.text', 'four')

If you pass a positive number, then it picks multiple elements or items

// yields jQuery object with 3 random items
cy.get('#items li').sample(3).should('have.length', 3)

See sample.cy.js

second

Yields the second element from the current subject. Could be an element or an array item.

cy.get('#items li').second().should('have.text', 'second')

See second.cy.js

third

Yields the third element from the current subject. Could be an element or an array item.

cy.get('#items li').third().should('have.text', 'third')

See third.cy.js

asEnv

Saves current subject in Cypress.env object. Note: Cypress.env object is reset before the spec run, but the changed values are passed from test to test. Thus you can easily pass a value from the first test to the second.

it('saves value in this test', () => {
  cy.wrap('hello, world').asEnv('greeting')
})

it('saved value is available in this test', () => {
  expect(Cypress.env('greeting'), 'greeting').to.equal('hello, world')
})

Do you really want to make the tests dependent on each other?

getInOrder

Queries the page using multiple selectors and returns the found elements in the specified order, no matter how they are ordered in the document. Retries if any of the selectors are not found.

cy.getInOrder('selector1', 'selector2', 'selector3', ...)
// yields a single jQuery subject with
// elements for selector1
// and selector2,
// and selector3, etc

You can also use a single array of selector strings

cy.getInOrder(['h1', 'h2', 'h3'])

stable

Sometimes you just want to wait until the element is stable. For example, if the element's text content does not change for N milliseconds, then we can consider the element to be text stable.

cy.get('#message').stable('text')
// yields the element

Supported types: text, value (for input elements), css, and element (compares the element reference)

You can control the quiet period (milliseconds), and pass the log and the timeout options

// stable for 500ms
// without logging
// with maximum retries duration of 6 seconds
cy.get('#message').stable('text', 500, { log: false, timeout: 6_000 })

When checking the CSS property to be stable, provide the name of the property:

// retries until the CSS animation finishes
// and the background color is red
cy.get('#message')
  .stable('css', 'background-color', 100)
  // yields the element
  .should('have.css', 'background-color', 'rgb(255, 0, 0)')

See stable.cy.js and stable-css.cy.js

detaches

experimental

Retries until the element with the given selector detaches from DOM.

cy.contains('Click to re-render').click()
cy.detaches('#list')

Sometimes the detachment can happen right with the action and the cy.detaches(selector) is too late. If you know the detachment might have already happened, you need to prepare for it by using an alias stored in the Cypress.env object:

cy.get('#name2').asEnv('name')
cy.contains('Click to remove Joe').click()
cy.detaches('@name')

The jQuery object will be stored inside the Cypress.env under the name property.

See detach.cy.js

difference

Computes an object/arrays of the difference with the current subject object/array.

cy.wrap({ name: 'Joe', age: 20 })
  .difference({ name: 'Joe', age: 30 })
  .should('deep.equal', { age: { actual: 20, expected: 30 } })

You can use synchronous predicate functions to validate properties

// confirm the value of the "age" property
// is larger than 15
.difference({ name: 'Joe', age: (n) => n > 15 })

Reports missing and extra properties. See difference.cy.js

Note: use have.length to validate the number of items in an array:

// let's check if there are 3 objects in the array
// INSTEAD OF THIS
.difference([Cypress._.object, Cypress._.object, Cypress._.object])
// USE AN ASSERTION
.should('have.length', 3)

You can check each item in the array subject using values / predicates from the expected object.

// list of people objects
cy.wrap(people)
  .difference({
    name: Cypress._.isString,
    age: (age) => age > 1 && age < 100,
  })
  .should('be.empty')

table

πŸ“ to learn more about cy.table command, read the blog post Test HTML Tables Using cy.table Query Command.

Extracts all cells from the current subject table. Yields a 2D array of strings.

cy.get('table').table()

You can slice the table to yield just a region .table(x, y, w, h)

Table

For example, you can get 2 by 2 subregion

cy.get('table')
  .table(0, 2, 2, 2)
  .should('deep.equal', [
    ['Cary', '30'],
    ['Joe', '28'],
  ])

See the spec table.cy.js for more examples.

Tip: you can combine cy.table with cy.map, cy.mapInvoke to get the parts of the table. For example, the same 2x2 part of the table could be extracted with:

cy.get('table')
  .table()
  .invoke('slice', 2, 4)
  .mapInvoke('slice', 0, 2)
  .should('deep.equal', [
    ['Cary', '30'],
    ['Joe', '28'],
  ])

Tip 2: to get just the headings row, combine .table and .its queries

cy.get('table')
  .table(0, 0, 3, 1)
  .its(0)
  .should('deep.equal', ['Name', 'Age', 'Date (YYYY-MM-DD)'])

To get the last row, you could do:

cy.get('table').table().invoke('slice', -1).its(0)

To get the first column joined into a single array (instead of array of 1x1 arrays)

cy.get('table')
  .table(0, 1, 1) // skip the heading "Name" cell
  // combine 1x1 arrays into one array
  .invoke('flatMap', Cypress._.identity)
  .should('deep.equal', ['Dave', 'Cary', 'Joe', 'Anna'])

toPlainObject

A query to convert special DOM objects into plain objects. For example, to convert DOMStringMap instance into a plain object compatible with deep.equal assertion we can do

cy.get('article')
  .should('have.prop', 'dataset')
  .toPlainObject()
  .should('deep.equal', {
    columns: '3',
    indexNumber: '12314',
    parent: 'cars',
  })

By default uses JSON stringify and parse back. If you want to convert using entries and fromEntries, add an argument:

cy.wrap(new URLSearchParams(searchParams)).toPlainObject('entries')

invokeOnce

In Cypress v12 cy.invoke became a query, which made working with asynchronous methods really unwieldy. The cy.invokeOnce is a return the old way of calling the method and yielding the resolved value.

cy.wrap(app)
  // app.fetchName is an asynchronous method
  // that returns a Promise
  .invokeOnce('fetchName')
  .should('equal', 'My App')

See the spec invoke-once.cy.js for more examples.

cy.invoke vs cy.map vs cy.mapInvoke

Here are a few examples to clarify the different between the cy.invoke, cy.map, and cy.mapInvoke query commands, see diff.cy.js

const list = ['apples', 'plums', 'bananas']

// cy.invoke
cy.wrap(list)
  // calls ".sort()" on the list
  .invoke('sort')
  .should('deep.equal', ['apples', 'bananas', 'plums'])

// cy.mapInvoke
cy.wrap(list)
  // calls ".toUpperCase()" on every string in the list
  .mapInvoke('toUpperCase')
  .should('deep.equal', ['APPLES', 'PLUMS', 'BANANAS'])

// cy.map
const reverse = (s) => s.split('').reverse().join('')
cy.wrap(list)
  // reverses each string in the list
  .map(reverse)
  .should('deep.equal', ['selppa', 'smulp', 'sananab'])
  // grabs the "length" property from each string
  .map('length')
  .should('deep.equal', [6, 5, 7])

Misc

mapChain

I have added another useful command (not a query!) to this package. It allows you to process items in the array subject one by one via synchronous, asynchronous, or cy command functions. This is because the common solution to fetch items using cy.each, for example does not work:

// fetch the users from a list of ids
// 🚨 DOES NOT WORK
cy.get(ids).each(id => cy.request('/users/' + id)).then(users => ...)
// Nope, the yielded "users" result is ... still the "ids" subject
// βœ… CORRECT SOLUTION
cy.get(ids).mapChain(id => cy.request('/users/' + id)).then(users => ...)

Types

This package includes TypeScript command definitions for its custom commands in the file commands/index.d.ts. To use it from your JavaScript specs:

/// <reference types="cypress-map" />

If you are using TypeScript, include this module in your types list

{
  "compilerOptions": {
    "types": ["cypress", "cypress-map"]
  }
}

The build process

The source code is in the src/commands folder. The build command produces ES5 code that goes into the commands folder (should not be checked into the source code control). The package.json in its NPM distribution includes commands plus the types from src/commands/index.d.ts file.

See also

  • cypress-should-really has similar functional helpers for constructing the should(callback) function on the fly.

Note: this module does not have filter method because Cypress API has query commands cy.filter and cy.invoke that you can use to filter elements in a jQuery object or items in an array. See the examples in the filter.cy.js spec. πŸ“Ί See video Filter Elements And Items With Retries.

Small print

Author: Gleb Bahmutov <gleb.bahmutov@gmail.com> Β© 2022

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