【问题标题】:Is there a way to mock a DOM before testing a React component?有没有办法在测试 React 组件之前模拟 DOM?
【发布时间】:2017-08-06 21:58:09
【问题描述】:

我正在尝试测试我的 React 类(使用 TestUtils、Enzyme 和 Jest),但由于我们不得不忍受一些变通方法,它依赖于服务器呈现的 HTML 页面中的元素——即,它会在渲染之前从 componentDidMount 中的 DOM 中抓取某些元素。例如:

componentDidMount() {
  document.documentElement.classList.add('example');
  this.someOtherFunction(document.getElementsByClassName('my-great-className'))
}

我想测试这个组件,但是 componentDidMount 中的函数当然会失败,因为测试中不存在服务器渲染的 HTML 页面。有没有办法在渲染 React 组件之前模拟一个特定的 DOM?

【问题讨论】:

    标签: reactjs dom jestjs enzyme


    【解决方案1】:

    您可以在开始测试之前设置这些内容

    global.document = {
      documentElement: {
        classList: {
          add: jest.fn()
        }
      }
      getElementsByClassName: jest.fn({id:'id'})
    }
    

    然后,在您的测试中,您可以检查 add 是用 example 调用的,someOtherFunction 是用 {id:'id'} 调用的。 由于所有测试文件都在其自己的沙箱中运行,因此可以完全安全地设置这样的文档模拟。

    【讨论】:

      猜你喜欢
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多