I'd like to write some Puppeteer-based tests to test some logic that makes use of the Gamepad API, but I can't find any documentation on the Puppeteer docs that explain how to simulate a gamepad and how to send button presses to the browser.
What's the proper way to do it?
There isn't really a "proper" way to do it.
What I've done is made a somewhat clean way you should be able to use. It essentially involves creating your own game controller management code to use in puppeteer, and injecting the controller state into a page using the puppeteer
evaluate
API call.Essentially we hijack the global scope
navigator.getGamepads
function and inject our own implementation.We start out by modelling a game controller in code. The most basic part of a controller is a button. So lets do that.
Next, according to the W3C Gamepad Specification a gamepad has two analog sticks, so we'll model those.
Finally, let's create a class to represent a game pad. This class will have a helper function that translates the controllers internal state to match the W3C Gamepad Interface signature.
Now we have a convenient way of representing a gamecontroller and its state in code, we can hijack
navigator.getGamepads
and replace it with our own function that returns the state of our virtual controllers.Now we'll define a couple of helper functions. One that sets the gamepads state that
navigator.getGamepads
will return.Now that we've done that, we need a way to trigger the
gamepadconnected
event. We can do that using the puppeteerpage.emit
function call.We now have all the building blocks to simulate a controller using puppeteer! Example usage is below:
Hopefully this should point you in the right direction. If you have any questions feel free to follow up here :)