Playwright · Reliable end-to-end tests
How do you simulate keyboard and mouse input?
Short answer
Prefer locator methods such as press, hover and dragTo. Use page.keyboard and page.mouse for low-level sequences that have no element-level equivalent.
Most interactions should target an element, because Playwright then performs actionability checks and focuses the right control. Low-level keyboard and mouse APIs are for shortcuts, canvas interaction and drag sequences that cannot be expressed with a locator.
const search = page.getByRole("searchbox", { name: "Search" });
await search.click();
await search.press("Control+A");
await search.pressSequentially("playwright");
await search.press("Enter");const source = page.getByRole("listitem", { name: "Task A" });
const target = page.getByRole("listitem", { name: "Done" });
await source.dragTo(target);
await page.mouse.move(100, 200);
await page.mouse.down();
await page.mouse.move(300, 200, { steps: 10 });
await page.mouse.up();Which API to reach for
locator.pressfor a key or shortcut on a focused elementlocator.pressSequentiallyfor typing character by characterlocator.hoverfor a hover statelocator.dragTofor dragging one element onto anotherpage.keyboardfor focus-independent shortcutspage.mousefor canvas drawing and coordinate-based movement
Keyboard shortcuts should use the platform modifier correctly. Control works on Windows and Linux, while macOS commonly uses Meta. If the suite runs on both, define a helper that selects the right modifier instead of hard-coding one.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between press and pressSequentially?
- 2How do you handle Control versus Meta on macOS?
- 3When is page.mouse necessary?
- 4Why is locator.click safer than clicking a coordinate?
Say it in the interview
I prefer locator-level input such as press, hover and dragTo, because Playwright focuses the element and runs actionability checks. I drop to the page keyboard and mouse APIs for canvas drawing, pixel-level drags or shortcuts that are not tied to a specific element. I also handle the macOS Meta versus Control difference instead of hard-coding one. Raw coordinates are the last resort because layout shifts can make them hit the wrong element.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Playwright mock interview and get scored feedback on depth, clarity and confidence.