(
{children}
);
const Header = () => (
Hello world
JD
Butler
lrc
);
### shallow render shallow render 相关的工具类存在于 `react-test-renderer/shallow` 空间下,我们首先引入,并创建一个实例:
import ShallowRenderer from ‘react-test-renderer/shallow’;
const renderer = new ShallowRenderer();
ShallowRenderer 的实例为我们提供了两个方法: * `render()` 用于 render 一个组件。你可以把 ShallowRenderer 的实例想象成一个容纳被 render 组件的“空间”。 * `getRenderOutput()` 在 render 之后,可以通过此命令获取 render 的结果。 让我们看看完整的例子:
describe(‘Header’, () => {
it(‘should render a top level div’, () => {
const renderer = new ShallowRenderer();
renderer.render(
);
const result = renderer.getRenderOutput();
expect(result.type).toBe(‘div’);
});
it(‘should render 3 Link’, () => {
const renderer = new ShallowRenderer();
renderer.render(
);
const result = renderer.getRenderOutput();
const childrenLink = result.props.children.filter(c => c.type === Link);
expect(childrenLink.length).toBe(3);
});
});
我们首先验证了 `Header` render 后顶层元素是一个 `div`。接着在第二个用例中验证了 render 结果中包含 3 个 `Link` 组件的实例。由于 shallow render 只 render 一层,所以可以验证的信息也都比较简单。比较适合验证组件输出的结构是否符合预期。 ### full render 接下来看看 full render。 首先引入工具库:
import TestRenderer from ‘react-test-renderer’;
调用 `TestRenderer` 的 `create` 方法并传入要 render 的组件就可以获得一个 `TestRenderer` 的实例。该实例上存在着以下几个方法和属性: * `.toJSON()`:生成一个表示 render 结果的 JSON 对象。该对象中只包含像 `<div>`(web 平台)或是 `<View` (native 平台)这样的原生节点。不会包含用户开发的组件的信息。适合用于 [snapshot testing](/go/?target=http%3A%2F%2Ffacebook.github.io%2Fjest%2Fdocs%2Fen%2Fsnapshot-testing.html%23snapshot-testing-with-jest)。 * `.toTree()`:和 `.toJSON()` 类似,但信息更加丰富,包含了用户开发的组件的信息。 * `.update(element)`:通过传入一个新的元素来更新上次 render 得到的组件树。 * `.umount()`:umount 组件树,同时触发相应的生命周期函数。 * `.getInstance()`:返回根节点对应的 React 组件实例,如果存在的话。如果顶级组件是一个函数式组件,则无法获取。 * `.root`:该属性保存了根节点对应的测试实例(test instance)。该实例为我们提供了一系列方法方便我们编写断言。 现在让我们看看测试实例上都有哪些方法和属性可供我们使用(完整列表请[参考这里](/go/?target=https%3A%2F%2Freactjs.org%2Fdocs%2Ftest-renderer.html%23testinstance): * `.find()` 与 `.findAll()`:用于查找符合特定条件的测试实例。区别在于 `.find()` 会严格要求节点树种只有 1 个满足条件的测试实例,如果没有或者多于 1 个就会抛出异常。此区别同样适用于下面两组方法。 * `.findByType()` 与 `.findAllByType`:用于查找特定类型的测试实例。这里的类型可以是 `div` 这种原生类型,也可以是 `Link` 这种用户编写的 React 组件。 * `.findByProps()` 与 `.findAllByProps()`:用于查找 props 符合特定结构的测试实例。 * `.instance`:该测试实例对应的 React 组件实例。 现在让我们看一个完整的测试用例:
describe(‘Header’, () => {
it(‘should render 3 a tag with className “my-link”‘, () => {
const testRenderer = TestRenderer.create(
);
const testInstance = testRenderer.root;
expect(testInstance.findAll(node => node.type === ‘a’ && node.props.className === ‘my-link’)).toHaveLength(3);
});
});
在这个用例中我们通过 `.find()` 方法查找了 `className` 为 `my-link` 的 `a` 标签并确保找到了 3 个。 ## react-dom/test-utils 使用方法 现在让我们来看看涉及到用户交互的组件如何编写单元测试。首先简单了解一下 `react-dom/test-utils` 的基本用法。 首先还是引入工具类:
import ReactTestUtils from ‘react-dom/test-utils’;
`ReactTestUtils` 对象上我们通常会用到以下一些方法(完整方法列表请参考[这里](/go/?target=https%3A%2F%2Freactjs.org%2Fdocs%2Ftest-utils.html)): * `.Simulate.{evnentName}()`:模拟在给定的 DOM 节点上触发特点事件。`Simulate` 可以触发[所有 React 支持的事件类型](/go/?target=https%3A%2F%2Freactjs.org%2Fdocs%2Fevents.html%23supported-events)。 * `renderIntoDocument()`:把一个 React 组件 render 到一个 detached 的 DOM 中。注意:该方法依赖 DOM 环境。不过不用担心,Jest 默认集成了 [jsdom](/go/?target=https%3A%2F%2Fgithub.com%2Fjsdom%2Fjsdom)。该方法会返回被 render 的 React 组件的实例。 * `scryRenderedDOMComponentsWithClass()` 与 `findRenderedDOMComponentWithClass()`:查找匹配特定类名的 DOM 元素。区别在于 `scryRenderedDOMComponentsWithClass()` 会查找所有元素。而 `findRenderedDOMComponentWithClass()` 会假定页面中有且只有 1 个符合条件的元素,否则抛出异常。 * `scryRenderedDOMComponentsWithTag()` 与 `findRenderedDOMComponentWithTag()`:查找匹配特定标签类型的 DOM 元素。 还是让我们通过一个具体的组件来熟悉下实际用法。 假设我们有以下 `Button` 组件:
import React from ‘react’;
class Button extends React.Component {
constructor() {
super();
this.state = { disabled: false }; this.handClick = this.handClick.bind(this);
}
handClick() {
if (this.state.disabled) { return }
if (this.props.onClick) { this.props.onClick() }
this.setState({ disabled: true });
setTimeout(() => {this.setState({ disabled: false })}, 200);
}
render() {
return (
{this.props.children}
);
}
};
export default Button;
其主要功能就是点击 `button` 元素时执行 `onClick` 回调,并且设置了自上一次点击之后,200 毫秒内按钮进入禁用状态。 首先让我们测试一下执行 `onClick` 回调这个逻辑:
it(‘should call onClick callback if provided’, () => {
const onClickMock = jest.fn();
const testInstance = ReactTestUtils.renderIntoDocument(
hello
);
const buttonDom = ReactTestUtils.findRenderedDOMComponentWithClass(testInstance, ‘my-button’);
ReactTestUtils.Simulate.click(buttonDom);
expect(onClickMock).toHaveBeenCalled();
});
这里我们创建了一个 mock 方法 `onClickMock` 并将它作为回到函数传递给 `Button` 组件。然后利用 `ReactTestUtils.Simulate.click` 模拟触发点击事件。最后确认一下 `onClickMock` 被调用。 注:关于 mock 方法的使用,在[上一篇文章中](/go/?target=https%3A%2F%2Floveky.github.io%2F2018%2F05%2F17%2Funit-test-and-jest%2F)有详细介绍,欢迎阅读。 接下来让我们测试一下点击过后 200 毫秒内进入禁用状态:
it(‘should be throttled to 200ms’, () => {
const testInstance = ReactTestUtils.renderIntoDocument(hello);
const buttonDom = ReactTestUtils.findRenderedDOMComponentWithClass(testInstance, ‘my-button’);
ReactTestUtils.Simulate.click(buttonDom);
expect(testInstance.state.disabled).toBeTruthy();
jest.advanceTimersByTime(199);
expect(testInstance.state.disabled).toBeTruthy();
jest.advanceTimersByTime(1);
expect(testInstance.state.disabled).toBeFalsy();
});
由于涉及到定时器逻辑,我们在这个用例中使用了 Jest 提供的 [timer mock 功能](/go/?target=https%3A%2F%2Ffacebook.github.io%2Fjest%2Fdocs%2Fen%2Ftimer-mocks.html)。详细用法请参考 Jest 官方文档。 ## Enzyme 前面已经介绍完了 React 自带的两个测试工具库。接下来简单介绍一下由 Airbnb 开源的 React 测试工具库 [Enzyme](/go/?target=http%3A%2F%2Fairbnb.io%2Fenzyme%2F)。 Enzyme 底层其实也是基于 `react-test-renderer` 和 `react-dom/test-utils` 的。但它在二者的基础上进行了封装提供了更加简单易用的查询、断言方法。在概念上,Enzyme 也与二者非常相似。在 Enzyme 中有三种 render 模式: 如果你能理解前面对 `react-test-renderer` 和 `react-dom/test-utils` 的介绍,那么上手 Enzyme 应该是非常容易的。此处不再详细介绍 Enzyme 的使用方法。 让我们使用 Enzyme 改写一下前面为 `Button` 组件编写的测试:
describe(‘Button’, () => {
it(‘should be throttled to 200ms’, () => {
const wrapper = mount(hello);
wrapper.find(‘.my-button’).simulate(‘click’);
expect(wrapper.state(‘disabled’)).toBeTruthy();
jest.advanceTimersByTime(199);
expect(wrapper.state(‘disabled’)).toBeTruthy();
jest.advanceTimersByTime(1);
expect(wrapper.state(‘disabled’)).toBeFalsy();
});
it(‘should call onClick callback if provided’, () => {
const onClickMock = jest.fn();
const wrapper = mount(hello