简体   繁体   中英

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. 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?

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. But I would expect P tag

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();
});

Note that it only works with React 15.4.0 and higher .

I used Enzyme-based test from this repo to solve this issue like that:

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

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

    const wrapper = shallow(<SomeComponent />);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM