Im trying to create unit tests for a angular project with Jest. Basically I have the test resolved with native html elements but I had to exchange them for web components and now the same code is not working.
Mainly I need to do the equivalence to this
let mockUlElement = document.createElement('ul');
For a web component call MurMenu (with tag <mur-menu>
) and the same for a li tag with MurMenuItem (with tag <mur-menu>
)
This doesnt work
let mockSixMenuElement = document.createElement('mur-menu');
This is my previous code for the whole test:
it('handleArrowUpDownEvent', () => {
let mockUlElement = document.createElement('ul');
let mockLiElement = document.createElement('li');
mockLiElement.focus = jest.fn();
let aElement = document.createElement('a');
aElement.click = jest.fn();
mockLiElement.appendChild(aElement);
mockUlElement.appendChild(mockLiElement);
component.searchResults = new ElementRef(mockUlElement)
component.selectedIndex = 1;
jest.spyOn(component.searchResults.nativeElement,
'querySelector').mockReturnValue(mockUlElement);
const eventArrowDown = new KeyboardEvent('keydown', { key: 'ArrowDown' });
component.searchFieldChanged = true;
component.handleArrowUpDownEvent(eventArrowDown);
expect(component.selectedIndex).toEqual(0);
component.handleArrowUpDownEvent(event);
expect(jest.spyOn(mockLiElement, 'focus' )).toHaveBeenCalled();
});
And this is my method:
@HostListener('document:keydown', ['$event'])
handleArrowUpDownEvent(event: KeyboardEvent) {
if (event.key === 'Escape') {
this.sixHeader.setSearchOpenState(false);
this.selectedIndex = 0;
}
if (this.searchFieldChanged === true) {
this.murMenuElement = this.searchResults.nativeElement.querySelector('mur-menu');
this.numberOfLiElements = this.murMenuElement ? this.murMenuElement.children.length : 0;
this.murMenuItemElements = this.searchResults.nativeElement.querySelectorAll(
'mur-menu > mur-menu-item',
);
for (let murMenuItem of this.murMenuItemElements) {
murMenuItem.setAttribute('tabindex', '0');
}
if (event.key === 'ArrowDown') {
this.selectedIndex = (this.selectedIndex + 1) % this.numberOfLiElements;
}
}
}