有没有人成功使用 react-testing-library 来测试 DraftJS 编辑器组件上的更改事件?

Jos*_*man 7 javascript testing reactjs draftjs react-testing-library

fireEvent.change()只是不起作用。

它说元素上没有设置器。

我尝试改用咏叹调选择器

const DraftEditor = getByRole('textbox')
DraftEditor.value ='something';
fireEvent.change(DraftEditor);
Run Code Online (Sandbox Code Playgroud)

我再次尝试使用查询选择器

const DraftEditor = container.querySelector('.public-DraftEditor-content'));
Run Code Online (Sandbox Code Playgroud)

改为尝试键盘事件。

没有。

有没有人设法使用draftjs 和反应测试库发送富文本输入文本?

小智 9

我通过从draft-js的一些问题描述中获得灵感并将其调整到我们手头的案例中来做到这一点

import { createEvent } from "@testing-library/dom"
import { render, fireEvent } from "@testing-library/react"
Run Code Online (Sandbox Code Playgroud)
function createPasteEvent(html) {
  const text = html.replace('<[^>]*>', '');
  return {
    clipboardData: {
      types: ['text/plain', 'text/html'],
      getData: (type) => (type === 'text/plain' ? text : html),
    },
  };
}
Run Code Online (Sandbox Code Playgroud)
renderedComponent = render(<App />)
const editorNode = renderedComponent.querySelector(".public-DraftEditor-content")
const eventProperties = createPasteEvent(textToPaste)
const pasteEvent = createEvent.paste(editorNode, eventProperties)
pasteEvent.clipboardData = eventProperties.clipboardData
fireEvent(editorNode, pasteEvent)
Run Code Online (Sandbox Code Playgroud)

一些补充说明:

  • 在我的例子中, renderComponent 是渲染 Editor 组件的父元素。
  • 显然,'ClipboardEvent' 没有在 JSDOM 中实现(参见支持事件列表),因此,调用 createEvent.paste 创建一个通用事件,而不是一个 ClipboardEvent。作为一种解决方法,我再次将必要的 clipboardData 属性复制到生成的通用事件中,以便Draft-js 编辑器的函数editOnPaste将它们考虑在内,该编辑器本身将因触发事件而被触发。