Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

userEvent in React Testing Library Doesn't Cause onClick To Be Called

I'm trying to run a really simple test with react-testing-library where a button is given a mock function, the button is clicked, and the test checks that the function was called. However, the test is currently failing because the function isn't being called. Here's the code:

import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

describe('Button', () => {
  test('eventHandler called on click', () => {
    const handleClick = jest.fn();
    render(
      <button onClick={handleClick} type="button">
        Click Me
      </button>
    );

    userEvent.click(screen.getByRole('button'));

    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});

No errors are thrown, the button is successfully found, but for some reason, the function doesn't register that it's been called.

Any help would be appreciated!

like image 673
Matt Stobbs Avatar asked Feb 02 '26 00:02

Matt Stobbs


2 Answers

I had the same problem, fireEvent works but the recommended userEvent doesn't trigger click handler. Turned out that userEvent is async. Below is my working test case.

test('Error message should show when all fields are blank', async () => {
  const user = userEvent.setup()
  render(<Signup />)
  
  await user.click(screen.getByRole('button'))

  expect(screen.getByTestId('errors'))
    .toHaveTextContent(dict.fields_must_not_be_empty)
})
like image 157
kimkunjj Avatar answered Feb 04 '26 12:02

kimkunjj


Worked fine for me Make sure you install this package @testing-library/user-event @testing-library/dom

Steps:

  1. npx create-react-app rtl-typescript --template typescript
  2. npx install --save-dev @testing-library/user-event @testing-library/dom
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

describe('Button', () => {
  test('eventHandler called on click', () => {
    const handleClick = jest.fn();
    render(
      <button onClick={handleClick} type="button">
        Click Me
      </button>
    );

    userEvent.click(screen.getByRole('button'));

    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});

enter image description here

In case needed, my package.json file dependencies

enter image description here

like image 39
Karthikeyan Avatar answered Feb 04 '26 14:02

Karthikeyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!