使用react-test-renderer的Jest快照测试中的Refs为null [英] Refs are null in Jest snapshot tests with react-test-renderer

查看:211
本文介绍了使用react-test-renderer的Jest快照测试中的Refs为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Currently I am manually initializing Quill editor on componentDidMount and jest tests fail for me. Looks like ref value that I am getting is null in jsdom. There is and issue here: https://github.com/facebook/react/issues/7371 but looks like refs should work. Any ideas what I should check?

组件:

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输出null。但是我希望P标签

As a result, console.log outputs null. But I would expect P tag

推荐答案

由于测试渲染器没有与React DOM耦合,所以它不知道什么是refs本来应该是这样的。 React 15.4.0为测试渲染器添加了模拟引用的功能,但你应该自己提供这些模拟 React 15.4.0发行说明包括这样做的一个例子。

Since test renderer is not coupled to React DOM, it doesn't know anything about what refs are supposed to look like. React 15.4.0 adds the ability to mock refs for test renderer but you should provide those mocks yourself. React 15.4.0 release notes include an example of doing so.

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及更高版本

这篇关于使用react-test-renderer的Jest快照测试中的Refs为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆