nick
nick

Reputation: 3229

React Testing Library jest.fn() toHaveBeenCalled() not working

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

Upvotes: 2

Views: 4394

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 121966

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

Upvotes: 3

dippas
dippas

Reputation: 60553

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

Upvotes: 2

Related Questions