jeudi 21 novembre 2019

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
  });
});

Aucun commentaire:

Enregistrer un commentaire