Home > Back-end >  React Testing Library jest.fn() toHaveBeenCalled() not working
React Testing Library jest.fn() toHaveBeenCalled() not working

Time:07-05

Component:

const MyComp = ({ handler }) => {
  return <button onClick={handler}>Test</button>
};

Test:

it('Calls the handler', async () => {
   const handler = jest.fn();
   render(<MyComp handler={handler} />);

   const button = screen.getByRole('button', { name: /Test/i });
   await fireEvent(button, new MouseEvent('click'));

   expect(handler).toHaveBeenCalled();
});

Expected number of calls: >= 1 Received number of calls: 0

CodePudding user response:

Try using userEvent.click, like this

it('Calls the handler', async () => {
   const handler = jest.fn();
   render(<MyComp handler={handler} />);

   const button = screen.getByRole('button', { name: /Test/i });
   await userEvent.click(button);

   expect(handler).toHaveBeenCalled();
});

CodePudding user response:

Three options:

  • Make the event bubble, as shown in the example (it doesn't return a promise, no await needed):

    fireEvent(button, new MouseEvent("click", { bubbles: true }));
    
  • Use the convenience method, which adds default event properties including bubbling (likewise):

    fireEvent.click(button);
    
  • Use userEvent (does return a promise, as of v14):

    await userEvent.click(button);
    
  • Related