如何在 Jest 单元测试中查看渲染的 React 组件是什么样的? [英] How to see what the rendered React component looks like in the Jest unit test?

查看:24
本文介绍了如何在 Jest 单元测试中查看渲染的 React 组件是什么样的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 React 组件进行测试.我需要检查渲染后的样子.尝试使用 ReactDOMServer.renderToString() 但它失败了.代码如下:

I'm trying to run a test for the React component. I need to check how it looks like after rendering. Tried to use ReactDOMServer.renderToString() but it fails. Here is the code:

import { NewRec } from '../src/components/edit';
import { shallow } from 'enzyme';
import React from 'react/lib/ReactWithAddons';
import ReactDOMServer from 'react-dom/server';

jest.mock('react-dom');
jest.mock('react/lib/ReactDefaultInjection');

describe('NewRec component', () => {
    const component = shallow(<NewRec />);
    it('returns true if blah blah', ()=>{
        var htmlstring = ReactDOMServer.renderToString(<component />);
    });
});

我收到以下错误:

Invariant Violation: There is no registered component for the tag component

我试着这样称呼它:var htmlstring = ReactDOMServer.renderToString(component); 然后我得到这个错误:

I tried to call it like: var htmlstring = ReactDOMServer.renderToString(component); then I get this error:

Invariant Violation: renderToString(): You must pass a valid ReactElement.

有人知道问题出在哪里吗?

Does anyone knows where the problem is?

推荐答案

快照功能 在 Jest 中,它将渲染的树存储为文件.请注意,您还必须安装 enzyme-to-json 以转换酶将组件渲染为快照方法可以理解的内容.

There is the snapshot feature in Jest where it stores the rendered tree as a file. Note that you have to install enzyme-to-json as well to convert the enzyme rendered component to something the snapshot method can understand.

import { NewRec } from '../src/components/edit';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';

describe('NewRec component', () = > {
  it('returns true if blah blah', () = > {
    const component = shallow(<NewRec />);
    expect(shallowToJson(component)).toMatchSnapshot();
  });
});

这将在您的测试文件夹中的 __snapshot__ 文件夹中创建一个新文件,您可以在其中检查渲染结果.每次重新运行测试时,都会针对快照测试组件.

This will create a new file in __snapshot__ folder in your test folder, where you can inspect the rendered result. Every time you rerun the test, the component will be tested against the snapshot.

这篇关于如何在 Jest 单元测试中查看渲染的 React 组件是什么样的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆