Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138163

how can I test if useState hook has been called with jest and react testing library?

$
0
0

I have this component that I would like to test using Jest and React testing library :

export function GenericDivider({ stepsHeader = [], componentsFactory = [] }) {
   const [currentPage, changePage] = useState(0);
   const Component = componentsFactory[currentPage] || (() => <></>);

   return (
    <div className="container page__container">
          ...
                 <a
                   href="#"
                   key={name}
                   onClick={e => {
                     e.preventDefault();
                     if (index < componentsFactory.length) changePage(index);
                   }}
                   className={`nav-link ${currentPage === index && 'active'}`}
                 >
                   {name}
                 </a>
          ...
    </div>
   );
}

export default memo(GenericDivider);

I would like to test if changePage is called when I fire a click, is there a way i can do that using Jest and React testing library ?

I'm new to testing and I tried this but it doesn't seem to work

it('Should call changePage when button clicked', () => {
    const changePage = jest.fn();

    const { container } = render(
      <GenericDivider
        stepsHeader={['hamid', 'walid', 'khalid']}
        componentsFactory={[() => <></>, () => <></>, () => <></>]}
      />,
    );

    const button = container.querySelector('a');
    fireEvent.click(button);
    expect(changePage).toHaveBeenCalled();
  });

Viewing all articles
Browse latest Browse all 138163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>