Refs are null in Jest snapshot tests with react-test-renderer
目前,我正在componentDidMount上手动初始化Quill编辑器,而Jest测试对我来说失败了。 看起来我得到的ref值在jsdom中为null。 这里有问题:https://github.com/facebook/react/issues/7371但看起来引用应该起作用。 有什么想法我应该检查吗?
零件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { componentDidMount() { console.log(this._p) } render() { return ( <img src={logo} className="App-logo" alt="logo" /> Welcome to React <p className="App-intro" ref={(c) => { this._p = c }}> To get started, edit <wyn>src/App.js</wyn> and save to reload. </p> ); } } |
测试:
1 2 3 4 5 6 7 8 9 10 11 | 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标签
由于测试渲染器未与React DOM耦合,因此它对ref的外观一无所知。 React 15.4.0增加了模拟测试渲染器的引用的功能,但是您应该自己提供这些模拟。 React 15.4.0发行说明包含一个示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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及更高版本。
我使用了此仓库中基于酶的测试来解决该问题,例如:
1 2 3 4 5 6 7 8 9 10 11 | import { shallow } from 'enzyme' import toJson from 'enzyme-to-json' describe('< SomeComponent />', () => { it('renders', () => { const wrapper = shallow(<SomeComponent />); expect(toJson(wrapper)).toMatchSnapshot(); }); }); |