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##=""