lundi 2 septembre 2019

Custom event parameter is not passed correctly in test

I developed a JavaScript library to handle the events generated by a gamepad/joystick, and I also developed a series of tests with Jest for different test cases. But I have a problem with the tests: I can't figure out how to simulate the gamepadconnected and gamepaddisconnected events.

This is a simplified version of my code:

const gameControl = {
  // ...
  init: function() {
    window.addEventListener('gamepadconnected', e => {
      console.log('gamepad detected');
      if (!window.gamepads) window.gamepads = {};
      if (e.gamepad) {
        if (!window.gamepads[e.gamepad.index]) {
          window.gamepads[e.gamepad.index] = e.gamepad;
          // ...
        }
      }
    });
    window.addEventListener('gamepaddisconnected', e => {
      console.log('gamepad disconnected');
      if (e.gamepad) {
        delete window.gamepads[e.gamepad.index];
        // ...
      }
    });
  }
  // ...
};

gameControl.init();

export default gameControl;

gamepadconnected and gamepaddisconnected are native events triggered when a gamepad/joystick is connected or disconnected respectively. As a parameter, they receive an event object with the gamepad property that is an object with information about the connected/disconnected gamepad.

I tried dispatching the events manually in the tests, creating my own custom event with the parameter I want (gamepads below is an array with gamepad's mock data). Something like this:

describe('gameControl', () => {

  // ...

  test('trigger gamepadconnected event', () => {
    const event = new CustomEvent('gamepadconnected', {
      detail: { gamepad: gamepads[0] }
    });
    global.dispatchEvent(event);
  });

  // as a different attempt, I placed gamepad directly at the top level
  test('trigger gamepaddisconnected event', () => {
    const event = new CustomEvent('gamepaddisconnected', {
      gamepad: gamepads[0]
    });
    global.dispatchEvent(event);
  });

  // ...

});

But, although the events are dispatched correctly and the event listener is triggered, the parameter doesn't make it through. For example, gamepadconnected is handled and I see in the console "gamepad detected," but the object e does not contain the property gamepad that I need.

I did a console.log(e) to see the properties of the event object, but my parameter is nowhere to be seen. This is all the console.log shows:

CustomEvent { isTrusted: [Getter] }

What am I doing wrong? How can I achieve what I want and test the full code of the event handler for gamepadconnected and gamepaddisconnected?

Aucun commentaire:

Enregistrer un commentaire