0
0
Cypresstesting~15 mins

Shadow DOM access in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify button click inside Shadow DOM updates text
Preconditions (1)
Step 1: Locate the custom element with id 'shadow-host'
Step 2: Access its Shadow DOM
Step 3: Find the button inside the Shadow DOM with class 'shadow-button'
Step 4: Click the button
Step 5: Verify that the paragraph inside the Shadow DOM with class 'shadow-text' updates to 'Button clicked!'
✅ Expected Result: After clicking the button inside the Shadow DOM, the paragraph text updates to 'Button clicked!'
Automation Requirements - Cypress
Assertions Needed:
Verify the button inside Shadow DOM is clickable
Verify the paragraph text inside Shadow DOM changes to 'Button clicked!' after click
Best Practices:
Use Cypress commands with .shadow() to access Shadow DOM elements
Use explicit assertions with .should() for verification
Avoid hardcoded waits; rely on Cypress automatic retries
Automated Solution
Cypress
describe('Shadow DOM Access Test', () => {
  beforeEach(() => {
    cy.visit('/shadow-dom-page')
  })

  it('Clicks button inside Shadow DOM and verifies text update', () => {
    cy.get('#shadow-host')
      .shadow()
      .find('.shadow-button')
      .should('be.visible')
      .click()

    cy.get('#shadow-host')
      .shadow()
      .find('.shadow-text')
      .should('have.text', 'Button clicked!')
  })
})

The test starts by visiting the page containing the Shadow DOM element.

We locate the host element with #shadow-host, then use .shadow() to access its Shadow DOM.

Inside the Shadow DOM, we find the button with class .shadow-button, check it is visible, and click it.

After clicking, we again access the Shadow DOM and find the paragraph with class .shadow-text, asserting its text changed to 'Button clicked!'.

This approach uses Cypress's built-in Shadow DOM support and avoids hard waits by relying on .should() which retries until the condition is met or times out.

Common Mistakes - 3 Pitfalls
Trying to access Shadow DOM elements without using .shadow() command
Using hardcoded waits like cy.wait(2000) before accessing Shadow DOM elements
{'mistake': 'Using global selectors ignoring Shadow DOM boundaries', 'why_bad': "Elements inside Shadow DOM are isolated; global selectors won't find them.", 'correct_approach': 'Scope selectors inside the Shadow DOM using .shadow() and .find() chained commands.'}
Bonus Challenge

Now add data-driven testing with 3 different buttons inside Shadow DOM that update text differently

Show Hint