vendredi 19 avril 2019

Testing hook that passes events to an element

I created a hook called useFocus with the following signature:

function useFocus<TElement extends HTMLElement>({
  onFocus?: React.FocusEventHandler<TElement>;
  onBlur?: React.FocusEventHandler<TElement>;
}): {
  isFocused: boolean;
  onFocus: React.FocusEventHandler<TElement>;
  onBlur: React.FocusEventHandler<TElement>;
}

I am trying to test focusing on the element and getting the isFocused flag to update. The following is how I am testing it:

import { renderHook } from 'react-hooks-testing-library';
import { render, fireEvent } from 'react-testing-library';
import { useFocus } from '../';

test('It should set flag on focus', () => {
  const { result } = renderHook(useFocus);
  expect(result.current.isFocused).toEqual(false);
  const { container } = render(<input
    onFocus={result.current.onFocus}
    onBlur={result.current.onBlur}
  />);
  fireEvent.focus(container);
  expect(result.current.isFocused).toEqual(true)
});

However, it seems like the flag is never set as intended. I'm sure this has to do with how the hooks library works with the testing library.

Is there a correct way to do this?

Aucun commentaire:

Enregistrer un commentaire