W3cubDocs

/Cypress

within

Scopes all subsequent cy commands to within this element. Useful when working within a particular group of elements such as a <form>.

Syntax

.within(callbackFn)
.within(options, callbackFn)

Usage

Correct Usage

cy.get('.list').within(($list) => {}) // Yield the `.list` and scope all commands within it

Incorrect Usage

cy.within(() => {})              // Errors, cannot be chained off 'cy'
cy.getCookies().within(() => {}) // Errors, 'getCookies' does not yield DOM element

Arguments

callbackFn (Function)

Pass a function that takes the current yielded subject as its first argument.

options (Object)

Pass in an options object to change the default behavior of .within().

Option Default Description
log true Displays the command in the Command log

Yields

  • .within() yields the same subject it was given from the previous command.

Examples

Forms

Get inputs within a form and submit the form

<form>
  <input name="email" type="email">
  <input name="password" type="password">
  <button type="submit">Login</button>
</form>
cy.get('form').within(($form) => {
  // you have access to the found form via
  // the jQuery object $form if you need it

  // cy.get() will only search for elements within form,
  // not within the entire document
  cy.get('input[name="email"]').type('[email protected]')
  cy.get('input[name="password"]').type('password')
  cy.root().submit()
})

Tables

Find row with specific cell and confirm other cells in the row

<table>
  <tr>
    <td>My first client</td>
    <td>My first project</td>
    <td>0</td>
    <td>Active</td>
    <td><button>Edit</button></td>
  </tr>
</table>
cy.contains('My first client').parent('tr').within(() => {
  // all searches are automatically rooted to the found tr element
  cy.get('td').eq(1).contains('My first project')
  cy.get('td').eq(2).contains('0')
  cy.get('td').eq(3).contains('Active')
  cy.get('td').eq(4).contains('button', 'Edit').click()
})

Rules

Requirements

  • .within() requires being chained off a previous command.

Assertions

  • .within() will only run assertions you've chained once, and will not retry.

Timeouts

  • .within() cannot time out.

Command Log

Get the input within the form

cy.get('.query-form').within((el) => {
  cy.get('input:first')
})

The commands above will display in the Command Log as:

Command Log within

When clicking on the within command within the command log, the console outputs the following:

Console Log within

History

Version Changes
< 0.3.3 .within() command added

See also

© 2020 Cypress.io
Licensed under the MIT License.
https://docs.cypress.io/api/commands/within.html