I have a function to add eventlisteners on multiple HTML nodes as written below. I am struggling to write unit tests for the function I am sending as a callback in those eventlisteners. This function is written to achieve accessibility requirements. Please help me to fix my unit tests. The result of the test is not covering if part. The code is written in JavaScript but it is used in Lit component.
Note: isMobile is a helper from function from util file. I have managed to write tests for addEventListener*. I need help only for handleFocus
function.
JS:
const handleFocus = (nextFocusElement, isShiftKey, onMobile = false) => (e) => {
const mobileCheck = isMobile() === onMobile;
const isTabPressed = e.key === 'Tab' || e.keyCode === 9;
const shiftKeyCheck = e.shiftKey === isShiftKey;
if (this.isProfileMenuActive && mobileCheck && isTabPressed && shiftKeyCheck) {
e.preventDefault();
nextFocusElement.focus();
}
};
const firstFocusableElementDesktop = this.shadowRoot?.querySelector('#profileInvoker');
const lastFocusableElementDesktop = this.shadowRoot.querySelector('#logout button');
firstFocusableElementDesktop.addEventListener('keydown', handleFocus(lastFocusableElementDesktop, true));
lastFocusableElementDesktop.addEventListener('keydown', handleFocus(firstFocusableElementDesktop, false));
const firstFocusableElementMobile = this.profileMenuElement.shadowRoot.querySelector('.aab-link-profile');
const lastFocusableElementMobile = this.profileMenuElement.shadowRoot.querySelector('button.close-icon');
firstFocusableElementMobile?.addEventListener('keydown', handleFocus(lastFocusableElementMobile, true, true));
lastFocusableElementMobile?.addEventListener('keydown', handleFocus(firstFocusableElementMobile, false, true));
}
Test:
it('something', () => {
profileInvokerMock.profileMenuElement = profileInvokerMock.shadowRoot?.querySelector('#profile-menu');
const firstFocusableElementDesktop = profileInvokerMock.shadowRoot?.querySelector('#profileInvoker');
profileInvokerMock.handleTrappedFocus();
const keyTab = new KeyboardEvent('keydown', { key: 'Tab' });
firstFocusableElementDesktop.dispatchEvent(keyTab);
const keyShift = new KeyboardEvent('keydown', { key: 'Shift' });
firstFocusableElementDesktop.dispatchEvent(keyShift);
isMobile.mockReturnValue(true);
firstFocusableElementDesktop.focus = jest.fn();
expect(firstFocusableElementDesktop.focus).toHaveBeenCalled();
});