JavaScript测试教程-part 2:引入 Enzyme 并测试 React 组件

做者:Marcin Wanago

翻译:疯狂的技术宅javascript

原文:https://wanago.io/2018/09/03/...前端

未经容许严禁转载java

在本教程的第一篇中,咱们简要介绍了单元测试的基础。此次要更进一步,使用 Enzyme 库测试 React。这样可使你的程序将更加可靠,而且更加容易避免回归。咱们在这里用了 Jest,不过 Enzyme 也能够与 MochaChai 之类的库一块儿使用。react

Enzyme 基础

Enzyme 是一个库,用于在测试时处理你的 React 组件。它由 Airbnb 开发。git

设置 Enzyme

继续上一篇文章的内容,假设你 Jest 已经可以工做了。若是尚未,请随时查看课程的上一部分。下面开始安装 Enzyme程序员

npm install enzyme

首先要建立一个 setupTests.js 文件。它将包含 adapter 的用法,后者是一个附加库,容许你将 Enzyme 与一组特定的 React 版本一块儿使用。我将使用 React 16.x,因此须要安装 enzyme-adapter-react-16。有关兼容性列表,请查看 Enzyme repogithub

你还能够找到 preactinferno之类的库的适配器
npm install enzyme-adapter-react-16

完成以后,setupTests.js 文件的内容应以下所示:面试

setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
 
configure({adapter: new Adapter()});

最后要作的是在 package.json 中提供此文件的路径npm

package.json
"jest": {
    "setupTestFrameworkScriptFile": "<rootDir>/app/setupTests.js"
}

准备就绪!json

浅渲染

Enzyme 库的最基本用法是浅渲染。它容许你仅渲染父组件。“浅渲染”不但速度更快,并且很是适合单元测试。这样,你就不比测试传递给 shallow 函数的其余组件。

App.js
import React from 'react';
 
const App = () => {
  return <h1>Hello world!</h1>
}
 
export default App;
App.test.js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
 
describe('app component', () => {
  it('contains a header with the "Hello world!"', () => {
    const app = shallow(<App/>);
    expect(app.containsMatchingElement(<h1>Hello world!</h1>)).toEqual(true);
  });
});

在这个简单测试中,咱们正在检查 App 组件是否包含某个标头。运行 npm run test 后,你会看到一条成功消息。

PASS  app/App.test.js
  app component
    ✓ contains a header with the "Hello world!"

这里要注意一个很是重要的点:即便咱们用了 Enzyme,但测试运行程序仍然是 Jest。因为咱们用的是 expect 函数,所以可使用各类可供调用的匹配器函数。我已经在课程的第一部分中提到了它们。相关列表,请访问 Jest 文档

让咱们建立一些更有趣的测试。先建立一个全新的组件。

ToDoList.js
import React from 'react';
 
const ToDoList = (props) => {
  return (
    <ul>
      {
        props.tasks.map((taskName, index) =>
          <li key={index}>{taskName}</li>
        )
      }
    </ul>
  )
};
 
export default ToDoList;

让咱们测试一下,若是提供的任务列表为空,将会发生什么,若是包含任务,又会发生什么。

ToDoList.test.js
import React from 'react';
import { shallow } from 'enzyme';
import ToDoList from './ToDoList';
 
describe('ToDoList component', () => {
  describe('when provided with an empty array of tasks', () => {
    it('contains an empty <ul> element', () => {
      const toDoList = shallow(<ToDoList tasks={[]}/>);
      expect(toDoList).toContainReact(<ul/>);
    })
    it('does not contain any <li> elements', () => {
      const toDoList = shallow(<ToDoList tasks={[]}/>);
      expect(toDoList.find('li').length).toEqual(0);
    })
  });
 
  describe('when provided with an array of tasks', () => {
    it('contains a matching number of <li> elements', () => {
      const tasks = ['Wash the dishes', 'Make the bed'];
      const toDoList = shallow(<ToDoList tasks={tasks}/>);
      expect(toDoList.find('li').length).toEqual(tasks.length);
    })
  });
});

测试顺利经过,可是咱们应该解释一些内容。

在第一个测试中,咱们使用了 toContainReact 函数,这是一个自定义匹配器函数。它是 enzyme-matchers 库的一部分。要将其与 Jest 一块儿使用,请安装 jest-enzyme 包。

npm install jest-enzyme

最后要作的是将其导入 setupTests 文件中。

setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-enzyme';
 
configure({adapter: new Adapter()});

有关其提供的功能列表,请查看自述文件。你会发现它很是有用。

在第二个测试中,咱们在组件上调用了 find 函数。这要归功于 shallow 函数返回 ShallowWrapper,它是渲染输出的包装器。它有一组可供调用的函数。要检查函数列表,请转到 Enzyme 文档

运行全部的测试会给咱们带来成功的信息!

PASS  app/App.test.js
PASS  app/components/ToDoList/ToDoList.test.js
 
Test Suites: 2 passed, 2 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        1.41s
Ran all test suites.

总结

本文中咱们已经了解了使用 Enzyme 测试 React 组件的基本知识。咱们已经介绍了安装 Enzyme 并运行第一个简单测试。使用的渲染类型称为“浅渲染”。之因此这样称呼,是由于它不渲染任何子组件。在编写单元测试时,它工做得很好。在本教程的后续部分中,我将介绍其余类型的渲染,并学习如何测试程序的不一样部分。它将包括快照测试和模拟数据之类的技术。下次见!


本文首发微信公众号:前端先锋

欢迎扫描二维码关注公众号,天天都给你推送新鲜的前端技术文章

欢迎扫描二维码关注公众号,天天都给你推送新鲜的前端技术文章


欢迎继续阅读本专栏其它高赞文章:


相关文章
相关标签/搜索