Search code examples
javascriptreactjsreact-testing-librarytesting-library

Remove character from behind using `Backspace` fireEvent


I try to remove a character from behind using the Backspace event but it didn't work as expected.

It won't let me delete the character from behind using the `Backspace.

input.focus()
const options = {
    key: 'Backspace',
    keyCode: 8,
    which: 8,
}
fireEvent.keyDown(input, options)
fireEvent.keyUp(input, options)

Reproduction: https://codesandbox.io/s/testing-library-delete-1-character-i4y3d?file=/src/input.test.js:507-753


Solution

  • I'm able to solve this issue by adding this function.

    function backspace(element) {
      let actuallyTyped = element.value;
    
      const backspaceKey = {
        key: 'Backspace',
        code: 8,
        inputType: 'deleteContentBackward',
      };
    
      const sharedEventConfig = {
        key: backspaceKey.key,
        charCode: backspaceKey.code,
        keyCode: backspaceKey.code,
        which: backspaceKey.code,
        modifier: backspaceKey.modifier,
      };
      const downEvent = fireEvent.keyDown(element, sharedEventConfig);
    
      if (downEvent) {
        actuallyTyped = actuallyTyped.slice(0, -1);
    
        fireEvent.input(element, {
          target: { value: actuallyTyped },
          inputType: backspaceKey.inputType,
          bubbles: true,
          cancelable: true,
        });
      }
    
      fireEvent.keyUp(element, sharedEventConfig);
    }
    

    And then calling it in my test task.

      // delete up 5 times
      let count = 5;
      do {
        backspace(input);
      } while (count--);