Unable to test if element is focusing using useHotkeys (hook version of React-hotkeys) in testing library

Viewed 125

So all I am doing is focusing an input element when user presses cmd+k shortcut.

Initially I was using window.eventListeners to achieve the functionality and my tests were also working fine. Recently I switched to a library(react hotkeys) to achieve the same. I have used 3 libraries so far and i am facing the same testing problem. Instead of focusing on the input, the element in focus is the entire body of my app.

my code (using chakra-ui)

    const inputref = useRef<HTMLInputElement>(null);
    useHotkeys('cmd+k', () => inputref?.current?.focus());

           <Search
            placeholder="Search"
            rightElement={
              <Badge colorScheme="badgeColors.grey" p={1}>
                {'⌘K'}
              </Badge>
            }
            onChange={(e) => _onSearchInputChange(e.target.value)}
            ref={inputref}
          />
        </Box>

   

My test

  it('focuses search input on ⌘k keys', () => {
    fireEvent.keyDown(document, { key: 'k', metaKey: true });
    const input = screen.getByRole('search');
    
    // userEvent.keyboard('{Meta}{k}'); //(using userEvent also didn't fix this)

    expect(input).toHaveFocus();
  });

the code I was using earlier, prior to using libraries

  const inputref = useRef<HTMLInputElement>(null);
  const focusHandler = useCallback((event: KeyboardEvent) => {
    if (event.metaKey && event.key === 'k') {
      event.preventDefault();
      inputref?.current?.focus();
    }
  }, []);

  useEffect(() => {
    document.addEventListener('keydown', focusHandler, false);

    return () => {
      document.removeEventListener('keydown', focusHandler, false);
    };
  }, [focusHandler]);

Tests seem to work fine in this case.

0 Answers
Related