1

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

nick
  • 2,819
  • 5
  • 33
  • 69
  • Why not userEvent.click? I don't think fireEvent returns a promise. – jonrsharpe Jul 04 '22 at 22:10
  • (Specifically to get _this_ to work, looks like your event needs to bubble, as in the example in the docs: https://testing-library.com/docs/dom-testing-library/api-events. Or just use the convenience method.) – jonrsharpe Jul 04 '22 at 22:26

2 Answers2

2

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);
    
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
1

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();
});
dippas
  • 58,591
  • 15
  • 114
  • 126