Javascript REF在带有react测试呈现器的Jest快照测试中为空

Javascript REF在带有react测试呈现器的Jest快照测试中为空,javascript,reactjs,jestjs,Javascript,Reactjs,Jestjs,目前我正在手动初始化componentDidMount上的Quill编辑器,jest测试失败。在jsdom中,我得到的ref值似乎为null。这里有一个问题:但看起来裁判应该起作用。你知道我应该检查什么吗 组成部分: import React,{Component}来自'React'; 从“/logo.svg”导入徽标; 导入“/App.css”; 类应用程序扩展组件{ componentDidMount(){ console.log(this.\u p) } render(){ 返回( 欢迎

目前我正在手动初始化componentDidMount上的Quill编辑器,jest测试失败。在jsdom中,我得到的ref值似乎为null。这里有一个问题:但看起来裁判应该起作用。你知道我应该检查什么吗

组成部分:

import React,{Component}来自'React';
从“/logo.svg”导入徽标;
导入“/App.css”;
类应用程序扩展组件{
componentDidMount(){
console.log(this.\u p)
}
render(){
返回(
欢迎反应

{this.\u p=c}> 要开始,请编辑

src/App.js
并保存以重新加载。

); }
}
由于测试渲染器没有耦合到React DOM,所以它不知道ref应该是什么样子。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();
});
从“React”导入React;
从“./App”导入应用程序;
从“反应测试渲染器”导入渲染器;
函数createNodeMock(元素){
if(element.type=='p'){
//这是的伪DOM节点。
//可以随意添加任何存根方法,例如focus()或
//防止组件崩溃所需的其他方法。
返回{};
}
//对于任何类型的DOM组件,都可以从该方法返回任何对象。
//在进行快照测试时,React将使用它作为引用,而不是DOM节点。
返回null;
}
它('正确渲染',()=>{
const options={createNodeMock};
//别忘了传递选项对象!
const tree=renderer.create(,options);
expect(tree.toMatchSnapshot();
});

请注意,它只对React 15.4.0及更高版本起作用。我使用基于酶的测试来解决这个问题,如下所示:

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

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

    const wrapper = shallow(<SomeComponent />);

    expect(toJson(wrapper)).toMatchSnapshot();
  });
});
从“酶”导入{shall}
从“酶到json”导入toJson
描述(“”,()=>{
它('呈现',()=>{
常量包装器=浅();
expect(toJson(wrapper)).toMatchSnapshot();
});
});

谢谢您的评论。我的使用案例是,我希望在安装组件后在DOM元素内呈现羽毛笔编辑器。我可能会返回类似document.createElement(“div”)的内容。但在这种情况下,渲染部分不会成为快照测试的一部分。有没有办法包含它?使用测试呈现程序进行快照测试并不适用于依赖DOM的部件。如果您需要测试DOM本身而不是反应组件,请考虑在JSDOM环境中使用Ac酶的<代码>(或)代码>。谢谢分享这个答案,这正是我所期待的。这个答案和发行说明链接都是完美的,但是有没有理由,实际文档不记录什么“代码>选项< /代码>?(例如,
createNodeMock
)是否可用?如果不可用,我可能会创建一个票证。