Selectors and the Cypress Command Queue
On this page
Two things decide whether a Cypress suite is pleasant to maintain: how you find elements, and whether you understand when your commands actually run. This chapter covers both, because the second explains most of the surprises people hit with the first.
Choosing selectors#
cy.get() takes a CSS selector, so anything CSS can express works. That does not make every selector a good one. Ranked from most to least robust:
| Selector | Example | Breaks when |
|---|---|---|
| Test attribute |
[data-cy=submit], [data-test=new-todo]
|
someone deletes the attribute |
| Text, scoped to an element | cy.contains('button', 'Save') |
the copy changes (which may be a bug you want to catch) |
id or name
|
#username, [name=email]
|
a developer renames it for unrelated reasons |
| Class or tag |
.btn-primary, button
|
styling or markup changes |
| Position | div > ul > li:nth-child(3) |
almost anything |
The Cypress documentation recommends dedicated data-* attributes, and the example app in this course already has one: the new-todo input is <input class="new-todo" data-test="new-todo">. Whether your team calls it data-cy, data-test or data-testid does not matter; pick one name and use it everywhere. A test attribute says "a test depends on this element", so nobody removes it during a redesign by accident.
When you cannot change the markup, scoped text is the next best thing, because it is what a user looks for too.
cy.get versus cy.contains#
cy.get(selector) yields every element that matches. cy.contains(text) yields the deepest element containing that text, and cy.contains(selector, text) yields the element matching the selector that contains the text. The second form is the one you want most of the time:
cy.contains('.todo-list li', 'Pay rent') // the <li>, not the <label> inside it
cy.contains('a', 'Completed').click() // the filter link, not some paragraph mentioning it
Both are queries: they retry until they find something or the timeout expires.
You need to click the "Completed" filter link in the footer. The word "Completed" also appears in a help paragraph above the list. Which command clicks the link reliably?
Without a selector, cy.contains yields the first deepest element containing the text, which may be the help paragraph. Scoping it to a says exactly what you want. cy.get('a') matches every link, and .click() refuses to click several elements unless you pass { multiple: true }.
Chaining and narrowing#
Commands chain: each one receives the subject the previous one yielded. Create cypress/e2e/selectors.cy.js:
describe('finding elements', () => {
beforeEach(() => {
cy.visit('/todo')
cy.get('[data-test=new-todo]').type('Pay rent{enter}')
})
it('completes one todo by its text', () => {
cy.contains('.todo-list li', 'Pay rent')
.find('.toggle')
.check()
cy.contains('.todo-list li', 'Pay rent').should('have.class', 'completed')
cy.get('.todo-count').should('contain', '2 items left')
})
it('filters to completed todos', () => {
cy.contains('.todo-list li', 'Pay rent').find('.toggle').check()
cy.contains('a', 'Completed').click()
cy.location('hash').should('eq', '#/completed')
cy.get('.todo-list li').should('have.length', 1).and('contain', 'Pay rent')
})
})
.find() searches inside the current subject, so .find('.toggle') gets the checkbox of that one row, not the first checkbox on the page. .first(), .last() and .eq(n) narrow by position, which is fine when the position is what you are testing ("the newest todo is at the bottom") and fragile otherwise.
When several commands work inside the same element, .within() scopes all of them:
cy.contains('.todo-list li', 'Walk the dog').within(() => {
cy.get('label').should('have.text', 'Walk the dog')
cy.get('.toggle').should('not.be.checked')
})
Every cy.get inside the callback only searches the matched <li>.
The command queue#
Here is the part that trips everyone up at least once. This does not work:
const input = cy.get('[data-test=new-todo]') // not an element
input.type('Buy milk{enter}') // happens to work, for the wrong reason
const count = cy.get('.todo-list li').length // undefined
When your it callback runs, no command has run yet. Each cy.* call only appends a command to a queue and returns a chainer object, so cy.get(...) returns that chainer, not a DOM element. After your function returns, Cypress takes the queue and runs one command at a time, waiting for each to finish (and retrying queries) before starting the next.
You can see the order directly. This test passes:
it('shows the order commands run in', () => {
const order = []
cy.get('.todo-list li').then(() => order.push('then'))
order.push('sync')
cy.then(() => {
expect(order).to.deep.equal(['sync', 'then'])
})
})
order.push('sync') is plain JavaScript and runs immediately, while the queued .then() callback runs later, so 'sync' comes first.
A test does let total; cy.get('.todo-list li').then(($li) => { total = $li.length }); cy.log(total). The log says undefined. Why?
Arguments are read when the command is added to the queue, which is before anything has run. Move the cy.log inside the .then() callback (or chain it after), so it is queued only once the value exists.
Getting values out: then, aliases and wrap#
Three tools cover almost every case where you need a value from the page.
.then() gives you the subject as a plain value (a jQuery-wrapped element for DOM queries), and any cy commands you call inside it are queued at that point:
it('reads a value with then()', () => {
cy.get('.todo-list li').its('length').then((count) => {
cy.log(`there are ${count} todos`)
expect(count).to.eq(3)
})
})
.its('length') reads a property of the subject; it retries like a query.
Aliases name a subject so later commands can refer to it:
cy.get('[data-test=new-todo]').as('input')
cy.get('@input').type('First{enter}')
cy.get('@input').type('Second{enter}')
cy.get('@input') re-runs the original query when it is used, so it does not hand you an element that the app has since replaced. Aliases also name network requests and stubs, which chapter 4 relies on.
cy.wrap(value) turns a plain value or promise into a subject, so you can chain assertions on it: cy.wrap({ total: 3 }).its('total').should('eq', 3).
Why does a Cypress test not need async/await, even though every command talks to the browser?
The chainers are not promises, and awaiting them does not do what you expect. The queue already serialises the commands; mixing in async/await only interleaves your synchronous code with it in confusing ways.
The next chapter builds on the queue: every query and assertion in it retries, which is why a Cypress suite should almost never wait a fixed number of milliseconds.