Simulate keydown on document for JEST unit testing

前端 未结 3 1748
清歌不尽
清歌不尽 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: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

提交回复
热议问题