How to trigger hotkeys from jest/test-library? #5891
-
I am using hotkeys using const hotkeys = [
{
global: true,
combo: 'mod+l',
label,
onKeyDown: onFocus,
group: 'group',
},
]
return <HotkeysTarget2 hotkeys={hotkeys}>
...
</HotkeysTarget2> This is working as intended. However, I am having trouble triggering the shortcut when testing my component with Jest/Testing-Library. I first tried to generate a keyboard event with const user = userEvent.setup()
render(<Component />)
await user.keyboard('{Meta>}l{/Meta}') While this correctly generates keyboard events, this won't trigger the I then looked at the const { container } = render(<Component />)
fireEvent.keyDown(container, {
// which code for 'l' key
which: 76,
metaKey: true
}) Unfortunately it still doesn't fire the Anyone has any idea on how to do fix the problem? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I found out why it wasn't working: the export const Aliases: IKeyMap = {
cmd: "meta",
command: "meta",
escape: "esc",
minus: "-",
mod: isMac() ? "meta" : "ctrl",
option: "alt",
plus: "+",
return: "enter",
win: "meta",
};
function isMac(platformOverride?: string) {
// HACKHACK: see https://github.com/palantir/blueprint/issues/5174
// eslint-disable-next-line deprecation/deprecation
const platform = platformOverride ?? (typeof navigator !== "undefined" ? navigator.platform : undefined);
return platform === undefined ? false : /Mac|iPod|iPhone|iPad/.test(platform);
} Since So in the end, this works as expected to trigger const { container } = render(<Component />)
fireEvent.keyDown(container, {
// which code for 'l' key
which: 76,
ctrlKey: true
}) |
Beta Was this translation helpful? Give feedback.
I found out why it wasn't working: the
mod
is converted toctrlKey
ormetaKey
by detecting the OS usingnavigator.platform
(another deprecated prop... :/):