Javascript 使用“Backspace”fireEvent从后面删除字符

Javascript 使用“Backspace”fireEvent从后面删除字符,javascript,reactjs,react-testing-library,testing-library,Javascript,Reactjs,React Testing Library,Testing Library,我尝试使用Backspace事件从后面删除一个字符,但它没有按预期工作 它不允许我使用`退格'从后面删除角色 input.focus() const options = { key: 'Backspace', keyCode: 8, which: 8, } fireEvent.keyDown(input, options) fireEvent.keyUp(input, options) 复制:我可以通过添加此函数来解决此问题 function backspace(ele

我尝试使用
Backspace
事件从后面删除一个字符,但它没有按预期工作

它不允许我使用`退格'从后面删除角色

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

复制:

我可以通过添加此函数来解决此问题

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);
}
然后在我的测试任务中调用它

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