本文转载自:众成翻译
译者:iOSDevLog
连接:http://www.zcfy.cc/article/3804
原文:https://www.fullstackreact.com/30-days-of-react/day-24/css
咱们先看一下咱们应用的一个特征,并考虑边缘案例的位置以及咱们假设将会发生的状况node
.让咱们从Timeline
组件开始, 由于它是咱们当前应用中最复杂的。react
Timeline
组件 显示 一个具备动态标题的标题的状态列表。咱们要测试咱们的组件中的任何动态逻辑。咱们必须从测试开始的最简单的逻辑是围绕Timeline
的动态标题。npm
咱们喜欢开始测试, 列出咱们对一个组件的假设, 以及在什么状况下这些假设是真实的。例如, 咱们能够对Timeline
组件进行假设的列表可能包括如下内容:app
在任何状况下, Timeline
将包含 一个有.notificationsFrame
类的<div />
。函数
在任何状况下, 咱们能够假设会有一个标题测试
在任何状况下, 咱们假设搜索按钮将开始隐藏spa
有至少四状态更新的列表翻译
这些 假设 将转化为咱们的测试。code
让咱们打开src/components/Timeline/__tests__/Timeline-test.js
文件。咱们在这个文件中留下了一些虚拟测试, 因此让咱们清除这些, 并开始一个新的描述块:
describe('Timeline', () => { // Tests go here })
对于咱们编写的针对React每一个测试的咱们都但愿测试文件导入React。咱们还要引入React测试实用程序:
import React from 'react'; import TestUtils from 'react-addons-test-utils'; describe('Timeline', () => { // Tests go here })
因为咱们在这里测试Timeline
组件, 所以咱们还但愿将其引入到咱们的工做区中:
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Timeline from '../Timeline'; describe('Timeline', () => { // Tests go here })
让咱们写第一个测试。咱们的第一个假设是很是简单的测试。咱们正在测试以确保元素被包装在.notificationsFrame
类中。在咱们编写的每一个测试中, 咱们都须要将应用呈如今工做测试文档中。react-addons-test-utils
库提供了一个函数来执行这个叫作renderIntoDocument()
:
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Timeline from '../Timeline'; describe('Timeline', () => { it('wraps content in a div with .notificationsFrame class', () => { const wrapper = TestUtils.renderIntoDocument(<Timeline />); }); })
若是咱们运行这个测试 (尽管咱们尚未设定任何指望), 咱们会发现测试代码有问题。React认为咱们正在尝试呈现一个未定义的组件:
让咱们在 DOM 中使用另外一个称为findRenderedDOMComponentWithClass()
的TestUtils
函数来找到咱们指望的元素。
findRenderedDOMComponentWithClass()
函数接受 两个 参数。第一个是渲染树 (咱们的wrapper
对象), 第二个是咱们但愿它查找的 css 类名:
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Timeline from '../Timeline'; describe('Timeline', () => { it('wraps content in a div with .notificationsFrame class', () => { const wrapper = TestUtils.renderIntoDocument(<Timeline />); const node = TestUtils .findRenderedDOMComponentWithClass(wrapper, 'notificationsFrame'); }); })
这样, 咱们的测试就会经过 (相信与否)。TestUtils 设置了一个指望, 即它能够在.notificationsFrame
类中找到该组件。若是它没有找到一个, 它将抛出一个错误, 咱们的测试将失败。
做为提醒, 咱们可使用 npm test
命令或yarn test
命令来运行测试。咱们将使用yarn test
命令, 由于咱们正在测试一个组件:
yarn test
经过咱们的一次测试, 咱们确认了咱们的测试设置正在运行。
不幸的是, TestUtils
的界面有点复杂和低级。enzyme
库是TestUtils
的封装, 提供一个更容易和 高级 的界面, 断言针对的React组件在测试。明天咱们将详细讨论酶。
今天的工做很好, 明天见!