react-testing: userEvent.click does not work
Asked Answered
C

2

17

I'm trying to use userEvent for testing UI interaction. However, it does not seem to work properly. I used this document as reference. Is there some necessary setup in order for it to work?

Here's the test code:

  test('A', () => {
    //setup
    const user = userEvent.setup();

    const sensing = jest.fn();
    const subject = (<button onClick={sensing}>testButton</button>);

    render(subject);

    // run
    user.click(screen.getByText('testButton'));

    // check
    expect(sensing).toBeCalledTimes(1);
  });

Using fireEvent.click instead of user.click does work.

Part of package.json

"react": "^18.1.0",
"react-dom": "^18.1.0",
"@storybook/react": "^6.4.22",
"@storybook/testing-library": "^0.0.9",
"@testing-library/dom": "^8.13.0",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.2.0",
"@testing-library/react-hooks": "^8.0.0",
"@testing-library/user-event": "^14.2.0",

...

Cestoid answered 4/8, 2022 at 8:48 Comment(1)
Does this answer your question? userEvent in React Testing Library Doesn't Cause onClick To Be CalledValentinevalentino
C
34

UserEvent needs await. So you want to write this:

  test('A', async () => {
    //setup
    const user = userEvent.setup();

    const sensing = jest.fn();
    const subject = (<button onClick={sensing}>testButton</button>);

    render(subject);

    // run
    await user.click(screen.getByText('testButton'));

    // check
    expect(sensing).toBeCalledTimes(1);
  });
Cestoid answered 4/8, 2022 at 8:48 Comment(2)
What about the right click or {button: 2} whatever? seems like not supported yetTypebar
Note that only UserEvent 14 or newer needs await. Every version before that was synchronousNeocene
I
2

The mock will not be called if the button you are clicking is disabled. This function will be called by fireEvent but not by a user event.Check if the button is disabled or not

Icicle answered 5/10, 2022 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.