简体   繁体   English

如何使用 React 测试库测试 `contenteditable` 事件

[英]How to test `contenteditable` events with React Testing Library

I am trying to write tests for one of our rich text components which was implemented with slate js editor in react js.我正在尝试为我们在 react js 中使用 slate js 编辑器实现的富文本组件之一编写测试。 So when writing tests, I am retrieveing the element div[contenteditable='true'], but not able to simulate events like change, blur, focus.因此,在编写测试时,我正在检索元素 div[contenteditable='true'],但无法模拟更改、模糊、焦点等事件。 The handlers attached to editor component are not getting called.附加到编辑器组件的处理程序没有被调用。 I tried multiple combinations, but no luck.我尝试了多种组合,但没有运气。 Can someone please help on this?有人可以帮忙吗? Is it possible to simulate events for contenteditable element using testing library (contenteditable is implemented using slatejs)?是否可以使用测试库模拟 contenteditable 元素的事件(contenteditable 是使用 slatejs 实现的)?

Like you've discovered, contenteditable isn't supported by JSDOM.就像你已经发现, contenteditable不JSDOM支持。 React Testing Library (RTL) is built on top of JSDOM, so it's not possible to test the Slate editor properly with RTL until JSDOM implements support for contenteditable . React 测试库 (RTL) 建立在 JSDOM 之上,因此在 JSDOM 实现对contenteditable支持之前,不可能使用 RTL 正确测试 Slate 编辑器。

Use a browser automation library together with Testing Library将浏览器自动化库与测试库一起使用

Your options are then to use a tool that creates a real browser context.然后您的选择是使用创建真实浏览器上下文的工具。 Testing Library have integrations with many tools that do exactly that:TestCafe , Cypress , Nightwatch , Puppeteer .测试库集成了许多工具,可以做到这一点:TestCafeCypressNightwatchPuppeteer

You can also use the above tools on their own, without Testing Library.您也可以自行使用上述工具,无需测试库。

I've solved this using Puppeteer, and there are two approaches:我已经使用 Puppeteer 解决了这个问题,有两种方法:

  1. Run a local server and tell Puppeteer to go to something like localhost:3000运行一个本地服务器并告诉 Puppeteer 去类似localhost:3000东西
  2. Set the content directly with page.setContent(htmlString)直接用page.setContent(htmlString)设置内容

(1) is the most common, and you'll find many guides for this since it's a common approach for end-to-end testing ( google search ). (1) 是最常见的,您会找到很多这方面的指南,因为它是端到端测试( 谷歌搜索)的常用方法。

(2) is a little trickier because you will have to transform and bundle your source for each test, and then inject it as HTML into the browser page. (2) 有点棘手,因为您必须为每个测试转换和捆绑源,然后将其作为 HTML 注入浏览器页面。 I prefer this approach because the testing experience is much more similar to using RTL.我更喜欢这种方法,因为测试体验更类似于使用 RTL。 I've created a repository with an example of this setup with the Slate editor here: https://github.com/marcusstenbeck/puppeteer-react-testing-template/我在此处使用 Slate 编辑器创建了一个包含此设置示例的存储库: https : //github.com/marcusstenbeck/puppeteer-react-testing-template/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM