Mocking Swipe in Playwright Testing
Deepankar Bhade /
While learning framer-motion I built a project which had tinder-cards swipe animations in it. I wanted to add e2e tests and was looking into playwright docs to find an API to do it. Unfortunately, I found an unsolved 2yo issue for touch/gestures support.
After skimming through a google search I figured out a way to implement it. Before getting into the solution let's look at what our test case is like. I move the cursor to the center of the card, hold it, move it to right/left, and release the cursor.
To mock the same in Playwright we can use the mouse API. First, we need to move the mouse to the center of the card, then hold it down, move to the destination and release it.
Mouse events to mock Swipe
To get the center coordinate of an element in playwright we can use the bounding box method, and calculate the center points based on its width, height & position.
// get the bounding box of active card const bb = await page.locator().boundingBox(); // get the center position of active card const center = { x: bb!.x + bb!.width / 2, y: bb!.y + bb!.height / 2 };
Here's the code to mock "swipe" based on mouse events.
// move the mouse to center (x,y) await page.mouse.move(x, y); // hold the mouse down await page.mouse.down(); // move the mouse to destination await page.mouse.move(x + 1000, y); // release the mouse await page.mouse.up();
Here's the test in action:
You can find the code for tests in this github repo .
This might not be the right way to mock swipe gestures in Playwright, but it works xD.
Hope this helps anyone out, Thank you