Skip to content

How to test components with ViewEncapsulation.ShadowDom? #290

Open

Description

@2YY

Hi, I'm testing component that used as WebComponent (Angular Element).

And I want to enable shadow DOM encapsulation.

@Component({
  // ...
  encapsulation: ViewEncapsulation.ShadowDom // <- This!
})

But if shadow DOM encapsulation is enabled, Angular Testing Library seems failed find elements in shadow DOM.

Is there anything I can solve this problem?

Thanks.

Activity

  1. timdeschryver commented on Mar 30, 2022

    @timdeschryver
    Member

    Hi, thanks for raising this issue.
    Unfortunately, we don't support shadow DOM for now.
    We're tracking this in DOM Testing Library, if it lands there, it should also be possible to use it with Angular Testing Library.

  2. ralfting commented on Feb 15, 2023

    @ralfting

    Hey @2YY, I had the same problem and I solved using this library (shadow-dom-testing-library), it works just fine for me.
    I hope soon we are getting support from Angular Testing Library to get elements in a Shadow DOM.

  3. jtrentes commented on Mar 7, 2024

    @jtrentes

    Is there any news on this topic? The tracked issue in DOM testing library has not been updated since 2022.

  4. cycleandsoak commented on Feb 7, 2025

    @cycleandsoak

    As a workaround, we override the view encapsulation of our Shadow Dom components for test.

    const TestSubject = overrideComponentViewEncapsulation(RealComponentWithShadowDom, ViewEncapsulation.None);
    
    // use TestSubject instead of RealComponentWithShadowDom in the test
    

    Here is the override function:

    export function overrideComponentViewEncapsulation<ComponentType extends Type<any>>(component: ComponentType, viewEncapsulation: ViewEncapsulation): ComponentType {
      const newComponentAnnotations: any = (component as any).__annotations__[0];
    
      @Component({
        ...newComponentAnnotations,
        encapsulation: viewEncapsulation,
      } as any)
      class NewComponent extends component {
    
      }
    
      Object.defineProperty(NewComponent, 'name', { value: component.name + 'WithViewEncapsulationOverride' });
      return NewComponent;
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions