在使用 react-test-renderer 的 Jest 快照测试中,Refs 为空

IT技术 javascript reactjs jestjs
2021-03-30 21:23:03

目前,我正在 componentDidMount 上手动初始化 Quill 编辑器,而 jest 测试对我来说失败了。看起来我得到的 ref 值在 jsdom 中为空。这里有问题:https : //github.com/facebook/react/issues/7371但看起来 refs 应该可以工作。任何想法我应该检查什么?

零件:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  componentDidMount() {
    console.log(this._p)
  }
  
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" ref={(c) => { this._p = c }}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

测试:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import renderer from 'react-test-renderer'

it('snapshot testing', () => {
    const tree = renderer.create(
        <App />
    ).toJSON()
    expect(tree).toMatchSnapshot()  
})

结果,console.log 输出空值。但我希望 P 标签

2个回答

由于测试渲染器未与 React DOM 耦合,因此它对 refs 应该是什么样子一无所知。React 15.4.0 添加了为测试渲染器模拟 refs 的能力,但你应该自己提供这些模拟React 15.4.0 发行说明包含这样做的示例。

import React from 'react';
import App from './App';
import renderer from 'react-test-renderer';

function createNodeMock(element) {
  if (element.type === 'p') {
    // This is your fake DOM node for <p>.
    // Feel free to add any stub methods, e.g. focus() or any
    // other methods necessary to prevent crashes in your components.
    return {};
  }
  // You can return any object from this method for any type of DOM component.
  // React will use it as a ref instead of a DOM node when snapshot testing.
  return null;
}

it('renders correctly', () => {
  const options = {createNodeMock};
  // Don't forget to pass the options object!
  const tree = renderer.create(<App />, options);
  expect(tree).toMatchSnapshot();
});

请注意,它仅适用于 React 15.4.0 及更高版本

感谢分享这个答案,这就是我正在寻找的。
2021-05-30 21:23:03
谢谢你的评论。我的用例是,一旦安装了组件,我想在 DOM 元素中呈现 Quill 编辑器。我可能会返回类似 document.createElement("div") 的东西。但在这种情况下,渲染部分不会成为快照测试的一部分。有没有办法包括它?
2021-06-07 21:23:03
使用测试渲染器的快照测试不适用于依赖 DOM 的部分。如果您需要测试DOM本身而不是React组件,请考虑mount()在jsdom环境中使用Enzyme
2021-06-08 21:23:03
这个答案和发行说明链接都是完美的,但实际create文档是否有任何理由不记录可用的内容options(例如createNodeMock)?如果没有,也许我会创建一张票。
2021-06-14 21:23:03

我使用了这个repo 中基于酶的测试来解决这个问题:

import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'

describe('< SomeComponent />', () => {
  it('renders', () => {

    const wrapper = shallow(<SomeComponent />);

    expect(toJson(wrapper)).toMatchSnapshot();
  });
});