Bird
Raised Fist0
Cypresstesting~8 mins

cy.within() for scoped queries in Cypress - Framework Patterns

Choose your learning style10 modes available
Framework Mode - cy.within() for scoped queries
Folder Structure
  cypress/
  ├── e2e/                  # Test files
  │   ├── login.cy.js       # Example test
  │   └── scopedQueries.cy.js  # Tests using cy.within()
  ├── fixtures/             # Test data files (JSON)
  │   └── users.json
  ├── support/              # Custom commands and utilities
  │   ├── commands.js       # Custom Cypress commands
  │   └── e2e.js            # Support file loaded before tests
  └── cypress.config.js     # Cypress configuration file
  
Test Framework Layers
  • Test Layer: Located in cypress/e2e/, contains test files using cy.within() to scope queries inside specific elements.
  • Support Layer: cypress/support/commands.js for reusable custom commands, e.g., commands that use cy.within() for scoped actions.
  • Fixtures Layer: cypress/fixtures/ holds test data like JSON files for data-driven tests.
  • Configuration Layer: cypress.config.js manages environment settings, base URLs, and browser options.
Configuration Patterns
  • Environment Variables: Use cypress.config.js to define baseUrl and environment-specific variables (e.g., env: { login_url: "/login" }).
  • Browser Selection: Configure browsers via CLI or cypress.config.js for cross-browser testing.
  • Credentials Management: Store sensitive data in cypress.env.json (ignored by git) or use environment variables to keep secrets safe.
  • Scoped Queries: Use cy.within() inside tests to limit query scope to a specific container element, improving test stability and readability.
Test Reporting and CI/CD Integration
  • Test Reports: Use Cypress built-in reporter or integrate with mochawesome for detailed HTML reports.
  • CI/CD Integration: Run Cypress tests in pipelines (GitHub Actions, GitLab CI, Jenkins) using cypress run command.
  • Artifacts: Save screenshots and videos on test failures for debugging scoped queries inside cy.within().
  • Parallelization: Use Cypress Dashboard service or CI parallel jobs to speed up test runs.
Best Practices
  1. Use cy.within() to scope queries: This reduces flakiness by limiting selectors to a specific container, like a form or modal.
  2. Prefer data-* attributes: Use data-cy or data-test attributes for stable selectors inside cy.within().
  3. Keep tests readable: Use cy.within() blocks to group related actions, making tests easier to understand.
  4. Avoid chaining long selectors: Instead of long CSS selectors, use cy.within() to break down queries into smaller scopes.
  5. Use custom commands: Wrap common cy.within() patterns into commands for reuse and cleaner tests.
Self Check

Where in this folder structure would you add a new custom command that uses cy.within() to fill out a login form?

Key Result
Use cy.within() to scope queries inside specific elements for stable and readable Cypress tests.

Practice

(1/5)
1. What is the main purpose of using cy.within() in Cypress tests?
easy
A. To run tests faster by skipping some steps
B. To select all elements on the page at once
C. To limit commands to a specific section of the page
D. To reset the browser state between tests

Solution

  1. Step 1: Understand the role of cy.within()

    cy.within() scopes all commands inside it to a specific part of the page, so only elements inside that section are targeted.
  2. Step 2: Compare with other options

    Options A, C, and D describe unrelated Cypress features. Only To limit commands to a specific section of the page correctly describes cy.within().
  3. Final Answer:

    To limit commands to a specific section of the page -> Option C
  4. Quick Check:

    Scope commands = Limit to section [OK]
Hint: Think of within as focusing on one page part [OK]
Common Mistakes:
  • Confusing cy.within() with global selectors
  • Thinking it speeds up tests by skipping steps
  • Assuming it resets browser state
2. Which of the following is the correct syntax to use cy.within() to scope commands inside a <form> element with id loginForm?
easy
A. cy.get('#loginForm').within(() => { /* commands */ })
B. cy.within('#loginForm', () => { /* commands */ })
C. cy.within(() => cy.get('#loginForm'))
D. cy.get('#loginForm').scope(() => { /* commands */ })

Solution

  1. Step 1: Recall correct cy.within() usage

    The correct pattern is to first get the element, then call within() with a callback containing scoped commands.
  2. Step 2: Analyze each option

    cy.get('#loginForm').within(() => { /* commands */ }) matches the correct syntax. cy.within('#loginForm', () => { /* commands */ }) is invalid because cy.within() does not take a selector as first argument. cy.within(() => cy.get('#loginForm')) misuses within by nesting get inside callback. cy.get('#loginForm').scope(() => { /* commands */ }) uses a non-existent scope method.
  3. Final Answer:

    cy.get('#loginForm').within(() => { /* commands */ }) -> Option A
  4. Quick Check:

    Get element then within callback = C [OK]
Hint: Always call within() on a selected element [OK]
Common Mistakes:
  • Passing selector directly to within()
  • Using non-existent methods like scope()
  • Nesting get inside within callback
3. Given the HTML below:
<div id="section1">
  <button class="btn">Click Me</button>
</div>
<div id="section2">
  <button class="btn">Don't Click Me</button>
</div>

What will the following Cypress code click?
cy.get('#section1').within(() => {
  cy.get('.btn').click()
})
medium
A. Throws an error because of multiple buttons
B. Clicks the button inside #section1 with text 'Click Me'
C. Clicks the button inside #section2 with text 'Don't Click Me'
D. Clicks both buttons with class 'btn'

Solution

  1. Step 1: Understand within() scope

    The within() limits commands to elements inside #section1. So cy.get('.btn') finds only the button inside #section1.
  2. Step 2: Identify clicked button

    The button inside #section1 has text 'Click Me', so that is clicked. Buttons outside #section1 are ignored.
  3. Final Answer:

    Clicks the button inside #section1 with text 'Click Me' -> Option B
  4. Quick Check:

    Scoped get clicks inside section1 only [OK]
Hint: Within limits get to one section only [OK]
Common Mistakes:
  • Thinking all buttons on page are clicked
  • Assuming error due to multiple buttons
  • Confusing which section is scoped
4. You wrote this Cypress test:
cy.within(() => {
  cy.get('.item').click()
})

But it fails with error: Cannot read property 'within' of undefined. What is the likely cause?
medium
A. The callback function is missing parentheses
B. The selector .item is incorrect
C. You cannot use within() with cy.get()
D. You forgot to select an element before calling within()

Solution

  1. Step 1: Analyze error message

    The error says within is called on undefined, meaning cy.within() is not a valid method.
  2. Step 2: Check usage of within()

    within() is a method on a selected element, like cy.get(...).within(). Calling cy.within() directly is invalid.
  3. Final Answer:

    You forgot to select an element before calling within() -> Option D
  4. Quick Check:

    Call within() on element, not on cy [OK]
Hint: Always select element before within() [OK]
Common Mistakes:
  • Calling within() directly on cy
  • Blaming selector instead of method usage
  • Ignoring error message details
5. You have two sections on a page, each with a button labeled 'Submit'. You want to click the 'Submit' button only inside the section with id form2. Which Cypress code correctly does this?
hard
A. cy.get('#form2').within(() => { cy.contains('Submit').click() })
B. cy.contains('Submit').click()
C. cy.get('button').contains('Submit').click()
D. cy.within('#form2', () => { cy.get('button').click() })

Solution

  1. Step 1: Identify the need for scoping

    Since there are multiple 'Submit' buttons, we must limit the search to the section with id form2 to avoid clicking the wrong button.
  2. Step 2: Check each option's correctness

    cy.get('#form2').within(() => { cy.contains('Submit').click() }) correctly uses cy.get('#form2').within() to scope commands, then finds and clicks the 'Submit' button inside. cy.contains('Submit').click() clicks the first 'Submit' button anywhere, which is unsafe. cy.get('button').contains('Submit').click() tries to chain contains incorrectly and is ambiguous. cy.within('#form2', () => { cy.get('button').click() }) uses invalid syntax for within().
  3. Final Answer:

    cy.get('#form2').within(() => { cy.contains('Submit').click() }) -> Option A
  4. Quick Check:

    Scope then find button inside = A [OK]
Hint: Use get then within to scope clicks [OK]
Common Mistakes:
  • Clicking buttons without scoping causes wrong clicks
  • Using within with selector argument
  • Misusing contains chaining
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard