< Back to Blog Overview

Using Mouse and Keyboard with Puppeteer

Using Mouse and Keyboard with Puppeteer

Mouse Actions with Puppeteer

Puppeteer provides a Mouse class which you can use by calling page.mouse in your test scripts. Every page object in Puppeteer has its own Mouse class, which is able to trigger synthetic mouse-events, which means it emulates the mouse.

As it's only providing synthetic events, it has some limitations, such as: no dragging and selecting text. (though you can use DocumentOrShadowRoot.getSelection() for that.

Mouse Control

Below is a simple example on how to use the mouse in your test scripts:

await page.mouse.move(0, 0);
await page.mouse.down();
await page.mouse.move(0, 100);
await page.mouse.up();

You can instruct the mouse to move to a specific coordinate (x, y). You can then issue a click (which is a mouse-down and mouse-up), or do the mouse up and down actions manually.

With the wheel command you can instruct the test to scroll up or down the page, with a deltaX or deltaY.

Keyboard actions with Puppeteer

The Keyboard class provides a virtual keyboard. You can use it to mimic typing in your tests. You can send raw characters, strings and even use key combinations. For example, hold SHIFT+ArrowUp.

For example, let's say you want to test a text editor where you type a word, and then want to highlight that word:

await page.keyboard.type('HeadlessTesting');
await page.keyboard.down('Shift');
for (let i = 0; i < ' World'.length; i++)
  await page.keyboard.press('ArrowLeft');

await page.keyboard.press('Backspace'); // remove the text?

To further mimic real user behaviour, you can specify the delay option:

await page.keyboard.type('Hi from HeadlessTesting', {delay: 100});

More information is available on the Puppeteer Documentation pages.

HeadlessTesting Logo

Sign up for a Free Trial

Start Headless Testing instantly.

No credit card required!