0
0
Cypresstesting~5 mins

cy.within() for scoped queries in Cypress

Choose your learning style9 modes available
Introduction

Use cy.within() to focus your test commands inside a specific part of the page. This helps avoid confusion when multiple similar elements exist.

When you want to test buttons or inputs inside a specific form without affecting others.
When a page has multiple sections with similar elements and you want to target only one section.
When you want to make your test clearer by limiting the search area for elements.
When you want to avoid accidentally clicking or typing in the wrong element on a complex page.
Syntax
Cypress
cy.get('selector').within(() => {
  // commands scoped inside this element
  cy.get('child-selector').click()
})

The within callback runs commands only inside the matched element.

This helps keep tests reliable and easier to read.

Examples
This scopes all commands inside the element with id login-form.
Cypress
cy.get('#login-form').within(() => {
  cy.get('input[name="username"]').type('user1')
  cy.get('input[name="password"]').type('pass123')
  cy.get('button[type="submit"]').click()
})
Checks that inside .product-list there are exactly 5 .product-item elements.
Cypress
cy.get('.product-list').within(() => {
  cy.get('.product-item').should('have.length', 5)
})
Sample Program

This test visits a page, then uses within to type inside a form only. It confirms the input inside the form has the typed value.

Cypress
describe('Scoped queries with cy.within()', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/actions')
  })

  it('types only inside the form using within', () => {
    cy.get('.action-form').within(() => {
      cy.get('.action-email').type('test@example.com').should('have.value', 'test@example.com')
      cy.get('.action-btn').click()
    })
  })
})
OutputSuccess
Important Notes

Always use clear selectors to avoid confusion inside within.

Commands inside within are chained to the scoped element, so no need to repeat the parent selector.

Summary

cy.within() limits commands to a specific part of the page.

It helps tests be more reliable and easier to understand.

Use it when you have similar elements in different sections.