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) => {
// 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()
})
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:
When clicking on the within command within the command log, the console outputs the following:
History
| Version | Changes |
|---|---|
| < 0.3.3 |
.within() command added |