Simulate keydown on document for JEST unit testing

前端 未结 3 1738
清歌不尽
清歌不尽 2020-12-18 20:45

Using JEST to unit test a component that has a keydown listener attached to the document.

How can I test this in JEST? How do I simulate t

相关标签:
3条回答
  • 2020-12-18 21:26

    Following @Iris Schaffer answer, If your code makes use of ctrl/alt/shift keys, you will need to init them, as well as mocking implementation of getModifierState method on KeyboardEvent

    const keyboardEvent = new KeyboardEvent('keydown', { keyCode, shiftKey, altKey, ctrlKey });
    jest.spyOn(keyboardEvent, 'getModifierState').mockImplementation((modifier) => {
         switch (modifier) {
              case 'Alt':
                   return altKey;
              case 'Control':
                   return ctrlKey;
              case 'Shift':
                   return shiftKey;
         }
    });
    
    0 讨论(0)
  • 2020-12-18 21:28

    I had the exact same problem and unfortunately couldn't find any details on how to solve this using TestUtils.Simulate. However this issue gave me the idea of simply calling .dispatchEvent with a KeyboardEvent inside my jest tests directly:

    var event = new KeyboardEvent('keydown', {'keyCode': 37});
    document.dispatchEvent(event);
    

    You can find details on the KeyboardEvent here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent

    0 讨论(0)
  • 2020-12-18 21:39

    You can also replace the whole document.eventListener with mock function before you mount the component:

    let events;
    document.addEventListener = jest.fn((event, cb) => {
      events[event] = cb;
    });
    

    And simulate event by calling events[event] after mounting, e.g.:

    events.keydown({ keyCode: 37 })
    

    Also, it's quite comfortable to do first part in beforeEach() function if you have many tests dealing with DOM events.

    0 讨论(0)
提交回复
热议问题