---
title: Selectors and the Cypress Command Queue | TestingBot
description: '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…'
source_url:
  html: https://testingbot.com/resources/courses/cypress/selectors-and-the-command-queue
  md: https://testingbot.com/resources/courses/cypress/selectors-and-the-command-queue.md
---

Course

[Cypress Tutorial: First Spec to CI](https://testingbot.com/resources/courses/cypress)

Chapter 3 of 11

1. [1 Cypress Tutorial for Beginners](https://testingbot.com/resources/courses/cypress)
2. [2 Install Cypress and Run a First Spec](https://testingbot.com/resources/courses/cypress/install-and-first-spec)
3. [3 Selectors and the Cypress Command Queue](https://testingbot.com/resources/courses/cypress/selectors-and-the-command-queue)
4. [4 Cypress Assertions and Waiting Without Sleeps](https://testingbot.com/resources/courses/cypress/assertions-and-waiting)
5. [5 Fixtures and Network Stubbing with cy.intercept](https://testingbot.com/resources/courses/cypress/fixtures-and-network-stubbing)
6. [6 Custom Commands and Logging In Once with cy.session](https://testingbot.com/resources/courses/cypress/custom-commands-and-sessions)
7. [7 Cypress Configuration, Environment Variables and Retries](https://testingbot.com/resources/courses/cypress/config-and-environment-variables)
8. [8 Cypress Component Testing vs End-to-End Testing](https://testingbot.com/resources/courses/cypress/component-testing)
9. [9 Run Cypress on TestingBot and in CI](https://testingbot.com/resources/courses/cypress/run-cypress-on-testingbot)
10. [10 Debugging Cypress Tests](https://testingbot.com/resources/courses/cypress/debugging-cypress-tests)
11. [11 Knowledge check](https://testingbot.com/resources/courses/cypress/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 3 of 11 Beginner 6 min read 3 quick checks Updated Nov 2026 

# Selectors and the Cypress Command Queue
[Watch this chapter Starts at 1:48 in the 9:03 course video.](https://www.youtube.com/watch?v=Ty406iWkgN4&t=108s)On this page
1. [Choosing selectors](https://testingbot.com#choosing-selectors)
2. [cy.get versus cy.contains](https://testingbot.com#cy-get-versus-cy-contains)
3. [Chaining and narrowing](https://testingbot.com#chaining-and-narrowing)
4. [The command queue](https://testingbot.com#the-command-queue)
5. [Getting values out: then, aliases and wrap](https://testingbot.com#getting-values-out-then-aliases-and-wrap)

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[#](https://testingbot.com#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[#](https://testingbot.com#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:

```javascript
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?

 `cy.contains('a', 'Completed').click()` `cy.contains('Completed').click()` `cy.get('a').click()`

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[#](https://testingbot.com#chaining-and-narrowing)

Commands chain: each one receives the **subject** the previous one yielded. Create `cypress/e2e/selectors.cy.js`:

```javascript
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:

```javascript
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[#](https://testingbot.com#the-command-queue)

Here is the part that trips everyone up at least once. This does **not** work:

```javascript
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:

```javascript
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?

 `.then()` cannot read the length of a jQuery object The list had not rendered yet, so the length was zero `cy.log` only prints strings The argument `total` is evaluated when `cy.log` is queued, before the `.then()` callback has run

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[#](https://testingbot.com#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:

```javascript
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:

```javascript
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?

 Cypress commands are synchronous and return elements immediately Commands are queued and Cypress runs them in order after the test function returns, so there is nothing to await Cypress adds `await` to every line when it bundles the spec

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.

[Previous · Chapter 2 Install Cypress and Run a First Spec](https://testingbot.com/resources/courses/cypress/install-and-first-spec) [Next · Chapter 4 Cypress Assertions and Waiting Without Sleeps](https://testingbot.com/resources/courses/cypress/assertions-and-waiting)

On this page

1. [Choosing selectors](https://testingbot.com#choosing-selectors)
2. [cy.get versus cy.contains](https://testingbot.com#cy-get-versus-cy-contains)
3. [Chaining and narrowing](https://testingbot.com#chaining-and-narrowing)
4. [The command queue](https://testingbot.com#the-command-queue)
5. [Getting values out: then, aliases and wrap](https://testingbot.com#getting-values-out-then-aliases-and-wrap)

Certification

Earn the free, resume-worthy TestingBot Cypress Certification for this course.

[How it works](https://testingbot.com/resources/courses/cypress/certification)
