Simulate keydown on document for JEST unit testing

前端 未结 3 1749
清歌不尽
清歌不尽 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;
         }
    });
    

提交回复
热议问题