0
0
Cypresstesting~5 mins

Shadow DOM access in Cypress

Choose your learning style9 modes available
Introduction

Shadow DOM hides parts of a web page to keep them separate. We need special ways to test these hidden parts.

Testing a web component that uses Shadow DOM to hide its internal structure.
Checking if a button inside a Shadow DOM responds to clicks.
Verifying text or elements inside a Shadow DOM are visible and correct.
Automating form filling inside a Shadow DOM element.
Debugging UI issues inside Shadow DOM components.
Syntax
Cypress
cy.get('selector').shadow().find('inner-selector')

cy.get() finds the outer element hosting the Shadow DOM.

shadow() tells Cypress to enter the Shadow DOM.

Examples
Finds a button inside the Shadow DOM of <my-component>.
Cypress
cy.get('my-component').shadow().find('button')
Finds a text input inside the Shadow DOM of <custom-element>.
Cypress
cy.get('custom-element').shadow().find('input[type="text"]')
Checks if the element with class 'title' inside Shadow DOM contains 'Hello'.
Cypress
cy.get('widget').shadow().find('.title').should('contain.text', 'Hello')
Sample Program

This test visits a page with a Shadow DOM. It finds a button inside the shadow root and clicks it. Then it checks if a paragraph inside the Shadow DOM shows 'Submitted'.

Cypress
describe('Shadow DOM Access Test', () => {
  it('checks button inside shadow root', () => {
    cy.visit('https://example.com/shadow')
    cy.get('shadow-host').shadow().find('button#submit').click()
    cy.get('shadow-host').shadow().find('p.status').should('have.text', 'Submitted')
  })
})
OutputSuccess
Important Notes

Always use shadow() before searching inside Shadow DOM.

Shadow DOM elements are hidden from normal DOM queries, so normal cy.get() won't find them.

Use unique and stable selectors inside Shadow DOM for reliable tests.

Summary

Shadow DOM hides parts of the page; special access is needed to test inside.

Use cy.get().shadow().find() to reach elements inside Shadow DOM.

Testing Shadow DOM ensures your web components work correctly.