Search code examples
javascriptintegration-testingmousetesting-library

Simulating a long press of mouse left button in JS with testing-library


I am writing an integration test and I need to click on an html object for longer than 0.5s. In the same test I have been able to use userEvent to handle various keys' actions, like:

  const user = userEvent.setup();
  await user.keyboard("[ShiftLeft>]"); // Press Shift (without releasing it)
  const pointer = await screen.findByText(objectName);
  await user.click(pointer);
  await user.keyboard("[/ShiftLeft]"); // Release Shift

I am wondering if there is a way of doing something similar (with or without userEvent) to perform a long click on an object in the page. Something like:

  • mouse left click on X without releasing button
  • wait 1s
  • release mouse left button

Thanks!


Solution

  • I found this solution to my problem, maybe it can be useful for others :) It uses the userEvent pointer from testing-library/user-event.

    export async function longPress(target: string) {
      const myTarget = await screen.findByText(target);
      const user = userEvent.setup();
      await user.pointer({
        keys: "[MouseLeft>]",
        target: myTarget ,
      });
      await new Promise((resolve) => {
        setTimeout(resolve, 1000);
      });
      await user.pointer({ keys: "[/MouseLeft]", target: myTarget });
    }