目前我手动初始化componentDidMount上的Quill编辑器,而且我的jest测试失败了。看起来我在jsdom中获得的ref值为null。这里有问题: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输出null。但我希望P标签
答案 0 :(得分:33)
由于测试渲染器未与React DOM耦合,因此它不知道任何refs应该是什么样子。 React 15.4.0为测试渲染器添加了模拟引用的功能,但你应该自己提供这些模拟。 React 15.4.0 release notes包含了这样做的一个例子。
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 :(得分:0)
我使用了repo中基于酶的测试来解决此问题:
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
describe('< SomeComponent />', () => {
it('renders', () => {
const wrapper = shallow(<SomeComponent />);
expect(toJson(wrapper)).toMatchSnapshot();
});
});