首页 > 解决方案 > 使用 @testing-library/react 测试 ag-grid

问题描述

我正在尝试测试使用 ag-grid 的组件。

当我进行断言以检查是否呈现具有给定文本的单元格时,我收到以下错误:

expect(received).toBeInTheDocument() received value must be an HTMLElement or an SVGElement. Received has type: object Received has value: HERE IS EXPECTED HTML FOR THE CELL I'VE BEEN LOOKING FOR

我已经为这个问题创建了代码沙箱(请参阅grid.test.tsxhttps://codesandbox.io/s/weathered-silence-4l1s1

标签: ag-gridreact-testing-library

解决方案


看起来 ag-grid 对 DOM 做了一些事情。在测试中渲染 ag-grid 后,它会在代码和框中使用时破坏所有检查 dom 的断言(即使是网格外的元素!)。我知道codeandbox 使用的是真正的浏览器dom 而不是jsdom。

我设法让它在我的本地机器上工作,但我不得不切换到 jsdom 14(检查https://github.com/ianschmitz/jest-environment-jsdom-fourteen)。

我还需要在我的测试设置中添加此代码(ag-grid 使用innerText而不是textContent,没有它我在渲染的单元格中没有文本)

Object.defineProperty(global.window.Element.prototype, 'innerText', {
  set(value) {
    this.textContent = value;
  },
  configurable: true
})

推荐阅读