使用React开玩笑 - 如何渲染整个组件并对其进行测试?

时间:2016-10-22 01:30:07

标签: unit-testing reactjs testing redux jestjs

假设我有一个简单的App组件,我正在运行测试,看看它是否只返回一个将Hello World打印到屏幕的div。为了在我的测试文件中呈现App,函数助手是什么?此外,为了测试正在呈现的HTML,在expect调用中调用的函数是什么?

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

describe("App", () => {
  it('prints "HELLO WORLD" to the screen', () => {
     expect(**App??**).**toRENDER??**("HELLO WORLD")
  }
}

由于

2 个答案:

答案 0 :(得分:1)

使用airbnb中的enzyme库是一种很好的做法。

共同使用example

您的代码可能如下所示:

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import {shallow} from 'enzyme'

describe("App", () => {
  it('prints "HELLO WORLD" to the screen', () => {
     const wrapper = shallow(<App />)

     expect(wrapper.text()).toBe("HELLO WORLD")
  }
}

答案 1 :(得分:1)

你想看看Jest的snapshot testing。这就像调用:

一样简单
import renderer from 'react-test-renderer';

describe('snapshot testing', () => {
  it('should render App', () => {
    const component = renderer.create(<App />);
    const tree = component.toJSON();
    expect(component).toMatchSnapshot();
  });
});

快照文件将存储在__tests__/__snapshots__文件夹中。 确保将这些快照文件提交到Git存储库中,以便其他贡献者可以为其组件创建快照。

有关如何使用React设置Jest快照测试的更多信息,请参阅此docs here,因为您需要安装一些npm依赖项。

相关问题