Skip to main content
Cypress App

Custom Queries

Starting in Cypress 12, Cypress comes with its own API for creating custom queries. The built in Cypress queries use the very same API that's explained below.

Queries are a type of command, used for querying the state of your application. Queries are different from other commands in that they follow three important rules:

  1. Queries are synchronous. Queries do not return or await promises.
  2. Queries are retriable. Once you return the inner function, Cypress takes control, handling retries on your behalf.
  3. Queries are idempotent. Once you return the inner function, Cypress invokes it repeatedly. Invoking the inner function multiple times must not change the state of your application.

With these rules, queries are simple to write and extremely powerful. Queries are the building blocks on which Cypress' API is built. To learn more about the differences between commands and queries, see our guide on Retry-ability.

info

If you want to chain together existing Cypress commands as a shortcut, you probably want to write a custom command instead.

Write a command instead of a query if your method needs to be asynchronous, or if it can be called only once.

info

We recommend defining queries in your cypress/support/commands.js file, since an import statement in the supportFile loads it before Cypress evaluates any test files.

Syntax​

Cypress.Commands.addQuery(name, callbackFn)
Cypress.Commands.overwriteQuery(name, callbackFn)

Usage​

Correct Usage

Cypress.Commands.addQuery('getById', function (id) {
return (subject) => newSubject
})

Cypress.Commands.overwriteQuery('get', function (originalFn, ...args) {
return originalFn.apply(this, args)
})

Arguments​

name (String)

The name of the query you're adding.

callbackFn (Function)

Pass a function that receives the arguments passed to the query.

Cypress invokes this outer function once. The outer function should return a function that takes a subject and returns a new subject; Cypress might call this inner function multiple times.

info

The query API relies on this to set timeouts, which means that callbackFn should always use function () {} and not be an arrow function (() => {}).

Examples​

.focused()​

You can think of the callback function as two separate parts. The outer function, which Cypress invokes once, where you perform setup and state management, and the query function, which Cypress might call repeatedly.

Let's look at an example. The example below is actual Cypress code — how .focused() is implemented internally, with some small adjustments to make it work from a support file. Use the TypeScript tab for a version that type-checks under strict TypeScript, or see Types for Custom Queries for additional guidance.

Cypress.Commands.addQuery('focused2', function focused2(options = {}) {
const log = options.log !== false && Cypress.log({ timeout: options.timeout })

this.set('timeout', options.timeout)

return () => {
let $el = cy.getFocused()

log &&
cy.state('current') === this &&
log.set({
$el,
consoleProps: () => {
return {
Yielded: $el?.length ? $el[0] : '--nothing--',
Elements: $el != null ? $el.length : 0,
}
},
})

if (!$el) {
$el = cy.$$(null)
$el.selector = 'focused'
}

return $el
}
})

The outer function​

Cypress calls the outer function once each time a test uses the query. The outer function performs setup and state management:

function focused2(options = {}) {
const log = options.log !== false && Cypress.log({ timeout: options.timeout })

this.set('timeout', options.timeout)

return () => { ... } // Inner function
}

Let's look at this piece by piece.

function focused2(options = {}) { ... }

Cypress passes the outer function whatever arguments the user calls it with, and does no processing or validation on the user's arguments. In our case, .focused2() accepts one optional argument, options.

If you wanted to validate the incoming arguments, you might add something like:

if (options === null || !_.isPlainObject(options)) {
const err = `cy.root() requires an \`options\` object. You passed in: \`{options}\``
throw new TypeError(err)
}

Throwing is a general pattern: when something goes wrong, queries throw an error. Cypress handles displaying the error in the Command Log.

const log =
options.log !== false &&
Cypress.log({
...(options.timeout !== undefined && { timeout: options.timeout }),
})

If the user has not set { log: false }, we create a new Cypress.log() instance. See Cypress.log() for more information.

This line is setup code, so it lives in the outer function - we only want it to run once, creating the log message when Cypress first begins executing this query. We hold onto a reference to Log instance. The inner function updates the log with additional details when it executes.

this.set('timeout', options.timeout)

When defining focused2(), we used function, rather than an arrow function. Using function gives us access to this, where we can set the timeout. If you don't call this.set('timeout'), or call it with null or undefined, your query uses the default timeout.

return () => { ... }

The inner function​

The outer function's return value is the inner function.

Cypress calls the inner function any number of times. Cypress first invokes the inner function repeatedly until it passes or the query times out; Cypress can then invoke it again later to determine the subject of future commands, or when the user retrieves an alias.

Cypress calls the inner function with one argument: the previous subject. Cypress performs no validation on this - it could be any type, including null or undefined.

.focused2() ignores any previous subject, but many queries do not - for example, .contains() accepts only certain types of subjects. You can use Cypress' builtin Cypress.ensure functions, as .contains() does: Cypress.ensure.isType(subject, ['optional', 'element', 'window', 'document'], 'contains', cy)

or you can perform your own validation and throw an error: if (!_.isString(subject)) { throw new Error('MyCustomCommand only accepts strings as a subject!') }

If the inner function throws an error, Cypress retries it after a short delay until it either passes or the query times out. This retry loop is the core of Cypress' retry-ability, and the guarantees it provides that your tests interact with the page as a user would.

Looking back to our .focused2() example:

return () => {
let $el = cy.getFocused()

log &&
cy.state('current') === this &&
log.set({
$el,
consoleProps: () => {
return {
Yielded: $el?.length ? $el[0] : '--nothing--',
Elements: $el != null ? $el.length : 0,
}
},
})

if (!$el) {
$el = cy.$$(null)
$el.selector = 'focused'
}

return $el
}

Piece by piece again:

let $el = cy.getFocused()

This line is the 'business end' of .focused2() - finding the element on the page that's currently focused.

log && cy.state('current') === this && log.set({...})

If log is defined (ie, the user did not pass in { log: false }), and this query is the current command, we update the log message with new information, such as $el (the subject we're about to yield from this query), and the consoleProps, a function that returns console output for the user.

if (!$el) {
$el = cy.$$(null)
$el.selector = 'focused'
}

If there's no focused element on the page, we create an empty jquery object.

return $el

The return value of the inner function becomes the new subject for the next command.

With this return value in hand, Cypress verifies any upcoming assertions, such as user's .should() commands, or if there are none, the default implicit assertions that the subject should exist.

Overwriting Existing Queries​

You can also modify the behavior of existing Cypress queries. Overwriting a query is useful to extend the functionality of builtin commands.

caution

Cypress.Commands.overwriteQuery can only overwrite queries, not other commands. If you want to modify the behavior of a non-query command, you need to use Cypress.Commands.overwrite instead.

info

Remember that query functions rely on this - when you invoke originalFn, be sure to use .call or .apply.

Cypress.Commands.overwriteQuery('get', function (originalFn, ...args) {
console.log('get called with args:', args)

const innerFn = originalFn.apply(this, args)

return (subject) => {
console.log('get inner function called with subject:', subject)

return innerFn(subject)
}
})

The originalFn is the function originally passed to Cypress.Commands.addQuery - it is a function that returns a function. This structure gives you access to both the outer arguments (before you call originalFn) and the inner function (the return value of originalFn), giving you a great deal of control over how the query executes.

Adding alias support to .contains()​

In this example, you extend cy.contains() to support querying for aliased subjects, like cy.contains('@foo').

Cypress.Commands.overwriteQuery(
'contains',
function (originalFn, filter, text, userOptions) {
if (_.isString(filter) && filter[0] === '@') {
let alias = cy.state('aliases')[filter.slice(1)]
let subject = cy.getSubjectFromChain(alias?.subjectChain)
filter = subject
}

if (_.isString(text) && text[0] === '@') {
let alias = cy.state('aliases')[text.slice(1)]
let subject = cy.getSubjectFromChain(alias?.subjectChain)
text = subject
}

return originalFn.call(this, filter, text, userOptions)
}
)

cy.wrap('li').as('element')
cy.wrap('asdf 1').as('content')

cy.contains('@element', '@content')

Validation​

As noted in the examples above, Cypress performs very little validation around queries - it is the responsibility of each implementation to ensure that its arguments and subject are of the correct type.

Cypress.ensure provides the same subject checks Cypress's built-in queries use, such as Cypress.ensure.isType() for the subject types a query accepts. A failed check throws a Cypress error that names your query, and Cypress retries it like any other error in the inner function. See the full list of Cypress.ensure functions.

You can also throw errors of any type inside your queries. Cypress catches and retries them the same way.

Notes​

Best Practices​

1. Don't make everything a custom query​

Custom queries work well when you're needing to describe behavior that's desirable across all of your tests. Examples would be cy.findBreadcrumbs() or cy.getLoginForm(). These queries are specific to your application and you can use them everywhere.

However, this pattern can be used and abused. Let's not forget - writing Cypress tests is JavaScript, and it's often more efficient to write a function for repeatable behavior than it is to implement a custom query.

2. Don't overcomplicate things​

Every custom query you write is generally an abstraction for locating elements on the page. That abstraction means you and your team members exert much more mental effort to understand what your custom command does.

There's no reason to add this level of complexity when the builtin queries are already quite expressive and powerful.

Don't do things like:

  • cy.getButton()
  • .getFirstTableRow()

Both of these queries are wrapping cy.get(selector). Wrapping cy.get() this way is completely unnecessary. Call .get('button') or .get('tr:first') instead.

Testing in Cypress is all about readability and simplicity. You don't have to do that much actual programming to get a lot done. You also don't need to worry about keeping your code as DRY as possible. Test code serves a different purpose than app code. Understandability and debuggability should be prioritized above all else.

Try not to overcomplicate things and create too many abstractions.

History​

VersionChanges
12.6.0overrideQuery API added
12.0.0addQuery API added

See also​