use*_*704 15 javascript reactjs jestjs
目前我手动初始化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>
);
}
}Run Code Online (Sandbox Code Playgroud)
测试:
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()
})Run Code Online (Sandbox Code Playgroud)
因此,console.log输出null.但我希望P标签
Dan*_*mov 35
由于测试渲染器未与React DOM耦合,因此它不知道任何refs应该是什么样子.React 15.4.0为测试渲染器添加了模拟引用的功能,但是你应该自己提供这些模拟.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();
});
Run Code Online (Sandbox Code Playgroud)
请注意,它仅适用于React 15.4.0及更高版本.
| 归档时间: |
|
| 查看次数: |
7584 次 |
| 最近记录: |