jeudi 24 décembre 2020

How to test react-hooks effectively?

I have used enzyme with karma/jasmine setup to test the hooks but there is a known issue with shallow rendering in enzyme useEffect not called when the component is shallow rendered that avoids me to use the shallow rendering. I tried it with deep rendering using mount api from enzyme. Every time setState is called by the useEffect hook, I have to wait for the update to happen and explicitly call the wrapper.update() method to assert on the latest DOM. Something like this:

Actual Code:

export const Component = (props) => {
    React.useEffect(() => {
        props.method();
    }, []);

    return (
        <Component />
    );
};

Unit Test:

import { mount } from 'enzyme';

it('should call prop on mount', () => {
  const methodSpy = jasmine.createSpy('method');
  const wrapper = mount(<Component method={methodSpy} />);

  wrapper.update();

  expect(methodSpy).toHaveBeenCalledTimes(1);
});

or (if useEffect makes an api call)

import { mount } from 'enzyme';

it('should call prop on mount', () => {
  const methodSpy = jasmine.createSpy('method');
  const wrapper = mount(<Component method={methodSpy} />);

  setTimeout(() => {
      wrapper.update();

      expect(methodSpy).toHaveBeenCalledTimes(1);
  });

which is not an elegant way to write tests I feel. So I wanted to know is the react-testing-library the only solution for testing hooks or is there any better way using enzyme that I am missing?

Help is appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire