8

I've recently been trying to use jasmine for some unit testing of a custom web component that utilises the shadow dom. The component takes in a text property and passes it to a child element to use as its text content, I'm trying to verify that the textContent is what it should be.

Every time I try to access the shadowRoot of my component, to then access its children, it simply returns null.

I've simplified some names but the code is the same.

Component:

@Component({
    tag: 'my-button',
    styleUrl: 'my-button.css',
    shadow: true,
})
export class MyButton {
    @Prop() text: string;
    @Prop() iconName: string;
    @Prop() url: string;

    render() {
        return (
            <div class="button-outer">
                <ion-button class="button" expand="block" href={this.url}>
                    <holo-icon class="button-icon" slotName="icon-only" iconName={this.iconName} />
                    <p class="button-label">{this.text}</p>
                </ion-button>
            </div>
        );
    }
}

HTML:

<my-button
    text="Test"
    icon-name="assets/svg/test-icon.svg"
    url="/test"
></my-button>

Test: (TestBed is setup as normal - async)

describe('has the expected html tags', () => {
    let buttons;

    beforeEach(() => {
        button = page.querySelector('my-button');
    });

    it('has text "Test"', () => {
        const label = button.shadowRoot.querySelector('div > ion-button > p');
        expect(label.textContent).toBe('Test');
    });
}

Karma Result: TypeError: Cannot read property 'querySelector' of null

The web component was developed in a separate project and imported in as an npm package, if that makes any difference?

I can create an element in the test, and attach a shadow root to it, and I can access and read its contents fine, just not actual elements that belong to the external page component I'm testing. It's really blocking me on other tests that use the shadow dom too. All I can find is answers suggesting fixture.detectChanges() but that doesn't seem to do anything.

Has anyone come across this or has a workaround or anything? Would be greatly appreciated :)

EDIT

I would just query the text attribute of my component if I knew how to preserve it, but it just gets replaced by _ngcontent-c##=""

HazeyAce
  • 361
  • 3
  • 12
  • Forgot to mention, I'm using another custom Icon element, but you can ignore that – HazeyAce Jan 17 '19 at 14:02
  • 2
    Its almost 3 years later, and probably you already forgot how you proceeded. But I am facing a similar issue. It looks like hardly anyone needs to test content of web components using shadowRoot. When running the tests with karma I can see the Text I want to expect, but I can't find a way to assert it is really there. It's frustrating. – trueunlessfalse Nov 12 '21 at 13:36

0 Answers0