[英]Refs are null in Jest snapshot tests with react-test-renderer
Currently I am manually initializing Quill editor on componentDidMount and jest tests fail for me.目前,我正在 componentDidMount 上手动初始化 Quill 编辑器,而 jest 测试对我来说失败了。 Looks like ref value that I am getting is null in jsdom.
看起来我得到的 ref 值在 jsdom 中为空。 There is and issue here: https://github.com/facebook/react/issues/7371 but looks like refs should work.
这里有问题: https : //github.com/facebook/react/issues/7371但看起来 refs 应该可以工作。 Any ideas what I should check?
任何想法我应该检查什么?
Component:成分:
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> ); } }
Test:测试:
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() })
As a result, console.log outputs null.结果,console.log 输出空值。 But I would expect P tag
但我希望 P 标签
Since test renderer is not coupled to React DOM, it doesn't know anything about what refs are supposed to look like.由于测试渲染器未与 React DOM 耦合,因此它对 refs 应该是什么样子一无所知。 React 15.4.0 adds the ability to mock refs for test renderer but you should provide those mocks yourself .
React 15.4.0 添加了为测试渲染器模拟 refs 的能力,但你应该自己提供这些模拟。 React 15.4.0 release notes include an example of doing so.
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();
});
Note that it only works with React 15.4.0 and higher .请注意,它仅适用于 React 15.4.0 及更高版本。
I used Enzyme-based test from this repo to solve this issue like that:我使用了这个repo 中基于酶的测试来解决这个问题:
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
describe('< SomeComponent />', () => {
it('renders', () => {
const wrapper = shallow(<SomeComponent />);
expect(toJson(wrapper)).toMatchSnapshot();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.