18

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",

...

1

2 Answers 2

35

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);
  });
Sign up to request clarification or add additional context in comments.

2 Comments

What about the right click or {button: 2} whatever? seems like not supported yet
Note that only UserEvent 14 or newer needs await. Every version before that was synchronous
3

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

1 Comment

Thank you. That solved it for me. I never realized my button was disabled until I double checked after your comment and saw a prop incorrectly setting it to disabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.