Drenai
Drenai

Reputation: 12407

Stencil unit test: access deeply nested Shadow DOM components

I have a Stencil.js component library with some nested elements that I'm unit testing

I'm using the newSpecPage helper functionality provided by Stencil:

const page = await newSpecPage({
    components: [CustomFileInput, CustomPanel],
    html: `
      <custom-file-input multiple>                    
      </custom-file-input>
    `
});

The CustomPanel component is nested within the CustomFileInput component. To query elements within CustomPanel I have to step down through Shadow DOM elements before being able to run a querySelector() command successfully

// page.root is the CustomFileInput HTML Element
const customPanelElement = page.root.shadowRoot.querySelector('custom-panel');
const queriedElemnt = customPanelElement.shadowRoot.querySelector('panel-child')

I'm wondering is there a more concise way to get a reference to the CustomPanel or panel-child elements rather than querying down through the components? In the above case there's just 2 components, but there could be more of course

Upvotes: 1

Views: 2588

Answers (1)

PradeepPathak
PradeepPathak

Reputation: 11

I presume you are using shadow:true so you have to use page.root.shadowRoot.querySelector('custom-panel')

What you can do is, you can assign reference inside beforeEach block

   const customPanelElement;
   const queriedElemnt;
   const page;

   beforeEach(async () => {
    page = await newSpecPage({
    components: [CustomFileInput, CustomPanel],
    html: `
      <custom-file-input multiple>                    
      </custom-file-input>
    `,
      supportsShadowDom: true
    });
    //Create reference here so that it is available inside every test case
    customPanelElement = page.root.shadowRoot.querySelector('custom-panel');
    queriedElemnt = customPanelElement.shadowRoot.querySelector('panel-child')
  });

Upvotes: 1

Related Questions