John Abraham
John Abraham

Reputation: 18791

How to get line coverage on React.useEffect hook when using Jest and enzyme?

Using React, enzyme and jest, How can I get code coverage on my closeDrawer() callback prop inside useEffect()

import React, {useEffect} from 'react';
import {Button} from './button';

const DrawerClose = ({closeDrawer}) => {
  useEffect(() => {
    const handleEsc = (e: any) => {
      if (e.key === 'Escape') {
        closeDrawer();
      }
    };
    window.addEventListener('keyup', handleEsc);
    return () => window.removeEventListener('keyup', handleEsc);
  });
  return (
    <Button>
      close
    </Button>
  );
};

export {DrawerClose};

Test:

import React from 'react';
import {DrawerClose as Block} from './drawer-close';

describe(`${Block.name}`, () => {
  it('should have drawer open', () => {
    const wrapper = shallow(<Block closeDrawer={() => 'closed'} />);
    expect(wrapper).toMatchSnapshot(); // will not hit the useEffect
  });
});

Upvotes: 3

Views: 4112

Answers (1)

skyboyer
skyboyer

Reputation: 23705

shallow() does not call useEffect yet. It's known issue #2086 and happens because of React's shallow renderer.

You can either use mount() and render completely or mock every/some nested component and still use mount() but having results more like shallow() could. Something like:

jest.mock('../../Button.jsx', (props) => <span {...props} />);

As for testing itself you need to ensure that closeDrawer will be called on hitting ESC. So we need to use spy and simulate simulate hitting ESC

const closeDrawerSpy = jest.fn();
const wrapper = mount(<Block closeDrawer={closeDrawerSpy} />);
// simulate ESC pressing

As for simulating ESC pressed on window, I'm not sure if jest-dom allows, you may try(taken from Simulate keydown on document for JEST unit testing)

var event = new KeyboardEvent('keyup', {'keyCode': 27});
window.dispatchEvent(event);

If that does not work(window.dispatchEvent is not a function or something alike) you always can mock addEventListener to have direct access to handlers.

Upvotes: 4

Related Questions