This repo shows you how to test React component. It is loosely based on Jack Franklin's article ["Testing React Applications"](http://12devsofxmas.co.uk/2015/12/day-2-testing-react-applications/).
![](app/img/react.png)
## Demo
```bash
$ git clone https://github.com/ruanyf/react-testing-demo.git
$ cd react-testing-demo && npm install
$ npm start
$ open http://127.0.0.1:8080
```
Now, you visit http://127.0.0.1:8080/, and should see a Todo app.
![](app/img/demo.png)
There are 5 places to test.
> 1. App's title should be "Todos"
> 1. Initial state of a Todo item should be right ("done" or "undone")
> 1. Click a Todo item, its state should be toggled (from "undone" to "done", or vice versa)
> 1. Click a Delete button, the Todo item should be deleted
> 1. Click the Add Todo button, a new Todo item should be added into the TodoList
All [test cases](https://github.com/ruanyf/react-testing-demo/tree/master/test) have been written. You run `npm test` to find the test result.
```bash
$ npm test
```
## Index
- [Testing Library](#testing-library)
- [React official Test Utilities](#react-official-test-utilities)
- [Shallow Rendering](#shallow-rendering)
- [renderIntoDocument](#renderintodocument)
- [findDOMNode](#finddomnode)
- [Enzyme Library](#enzyme-library)
- [shallow](#shallow)
- [render](#render)
- [mount](#mount)
- [API List](#api-list)
- [License](#license)
## Testing Library
The most important tool of testing React is [official Test Utilities](https://facebook.github.io/react/docs/test-utils.html), but it only provides low-level API. As a result, some third-party test libraries are built based on it. Airbnb's [Enzyme library](https://github.com/airbnb/enzyme) is the easiest one to use among them.
Thus every test case has at least two ways to write.
> - Test Utilities' way
> - Enzyme's way
This repo will show you both of them.
## React official Test Utilities
Since a component could be rendered into either a virtual DOM object (`React.Component`'s instance) or a real DOM node, [Test Utilities](https://facebook.github.io/react/docs/test-utils.html) library gives you two testing choices.
> - **Shallow Rendering**: testing a virtual DOM object
> - **DOM Rendering**: testing a real DOM node
### Shallow Rendering
[Shallow Rendering](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) just renders a component "one level deep" without worrying about the behavior of child components, and returns a virtual DOM object. It does not require a DOM, since the component will not be mounted into DOM.
At first, import the Test Utilities in your test case script.
```javascript
import TestUtils from 'react-addons-test-utils';
```
Then, write a Shallow Rendering function.
```javascript
import TestUtils from 'react-addons-test-utils';
function shallowRender(Component) {
const renderer = TestUtils.createRenderer();
renderer.render(<Component/>);
return renderer.getRenderOutput();
}
```
In the code above, we define a function `shallowRender` to return a component's shallow rendering.
The [first test case](https://github.com/ruanyf/react-testing-demo/blob/master/test/shallow1.test.js) is to test the title of `App`. It needn't interact with DOM and doesn't involve child-components, so is most suitable for use with shadow rendering.
```javascript
describe('Shallow Rendering', function () {
it('App\'s title should be Todos', function () {
const app = shallowRender(App);
expect(app.props.children[0].type).to.equal('h1');
expect(app.props.children[0].props.children).to.equal('Todos');
});
});
```
You may feel `app.props.children[0].props.children` intimidating, but it is not. Each virtual DOM object has a `props.children` property which contains its all children components. `app.props.children[0]` is the `h1` element whose `props.children` is the text of `h1`.
The [second test case](https://github.com/ruanyf/react-testing-demo/blob/master/test/shallow2.test.js) is to test the initial state of a `TodoItem` is undone.
At first, we should modify the function `shallowRender` to accept second parameter.
```javascript
import TestUtils from 'react-addons-test-utils';
function shallowRender(Component, props) {
const renderer = TestUtils.createRenderer();
renderer.render(<Component {...props}/>);
return renderer.getRenderOutput();
}
```
The following is the test case.
```javascript
import TodoItem from '../app/components/TodoItem';
describe('Shallow Rendering', function () {
it('Todo item should not have todo-done class', function () {
const todoItemData = { id: 0, name: 'Todo one', done: false };
const todoItem = shallowRender(TodoItem, {todo: todoItemData});
expect(todoItem.props.children[0].props.className.indexOf('todo-done')).to.equal(-1);
});
});
```
In the code above, since [`TodoItem`](https://github.com/ruanyf/react-testing-demo/blob/master/app/components/TodoItem.jsx) is a child component of [`App`](https://github.com/ruanyf/react-testing-demo/blob/master/app/components/App.jsx), we have to call `shallowRender` function with `TodoItem`, otherwise it will not be rendered. In our demo, if the state of a `TodoItem` is undone, the `class` property (`props.className`) contains no `todo-done`.
### renderIntoDocument
The second testing choice of official Test Utilities is to render a React component into a real DOM node. `renderIntoDocument` method is used for this purpose.
```javascript
import TestUtils from 'react-addons-test-utils';
import App from '../app/components/App';
const app = TestUtils.renderIntoDocument(<App/>);
```
`renderIntoDocument` method requires a DOM, otherwise throws an error. Before running the test case, DOM environment (includes `window`, `document` and `navigator` Object) should be available. So we use [jsdom](https://github.com/tmpvar/jsdom) to implement the DOM environment.
```javascript
import jsdom from 'jsdom';
if (typeof document === 'undefined') {
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = global.window.navigator;
}
```
We save the code above into [`test/setup.js`](https://github.com/ruanyf/react-testing-demo/blob/master/test/setup.js). Then modify `package.json`.
```javascript
{
"scripts": {
"test": "mocha --compilers js:babel-core/register --require ./test/setup.js",
},
}
```
Now every time we run `npm test`, `setup.js` will be required into test script to run together.
The [third test case](https://github.com/ruanyf/react-testing-demo/blob/master/test/dom1.test.js) is to test the delete button.
```javascript
describe('DOM Rendering', function () {
it('Click the delete button, the Todo item should be deleted', function () {
const app = TestUtils.renderIntoDocument(<App/>);
let todoItems = TestUtils.scryRenderedDOMComponentsWithTag(app, 'li');
let todoLength = todoItems.length;
let deleteButton = todoItems[0].querySelector('button');
TestUtils.Simulate.click(deleteButton);
let todoItemsAfterClick = TestUtils.scryRenderedDOMComponentsWithTag(app, 'li');
expect(todoItemsAfterClick.length).to.equal(todoLength - 1);
});
});
```
In the code above, first, `scryRenderedDOMComponentsWithTag` method finds all `li` elements of the `app` component. Next, get out `todoItems[0]` and find the delete button from it. Then use `TestUtils.Simulate.click` to simulate the click action upon it. Last, expect the new number of all `li` elements to be less one than the old number.
Test Utilities provides many methods to find DOM elements from a React component.
> - [scryRenderedDOMComponentsWithClass](https://facebook.github.io/react/docs/test-utils.html#scryrendereddomcomponentswithclass): Finds all instances of components in the rendered tree that are DOM components with the class name matching className.
> - [findRenderedDOMComponentWithClass](https://facebook.github.io/react/docs/test-utils.html#findrendereddomc
没有合适的资源?快使用搜索试试~ 我知道了~
React组件测试教程_JavaScript_CSS_下载.zip
共30个文件
js:10个
png:5个
jsx:5个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 160 浏览量
2023-04-21
10:34:48
上传
评论
收藏 135KB ZIP 举报
温馨提示
React组件测试教程_JavaScript_CSS_下载.zip
资源推荐
资源详情
资源评论
收起资源包目录
React组件测试教程_JavaScript_CSS_下载.zip (30个子文件)
react-testing-demo-master
.eslintrc 258B
webpack.config.js 971B
.jshintignore 13B
.jshintrc 131B
app
main.css 275B
components
App.jsx 273B
TodoList.jsx 694B
AddTodo.jsx 626B
TodoItem.jsx 705B
img
demo-delete.png 16KB
react.png 50KB
demo-toggle.png 21KB
demo-newitem.png 22KB
demo.png 20KB
main.jsx 187B
index.html 212B
stores
TodoStore.js 1KB
.babelrc 249B
package.json 2KB
test
setup.js 233B
shallow2.test.js 675B
dom2.test.js 758B
dom3.test.js 784B
dom1.test.js 702B
enzyme1.test.js 1KB
shallow1.test.js 625B
.gitignore 34B
.eslintignore 35B
README.md 16KB
webpack.production.config.js 977B
共 30 条
- 1
资源评论
快撑死的鱼
- 粉丝: 1w+
- 资源: 9156
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- #P0015. 全排列 超级简单
- pta题库答案c语言之排序4统计工龄.zip
- pta题库答案c语言之树结构7堆中的路径.zip
- pta题库答案c语言之树结构3TreeTraversalsAgain.zip
- pta题库答案c语言之树结构2ListLeaves.zip
- pta题库答案c语言之树结构1树的同构.zip
- 基于C++实现民航飞行与地图简易管理系统可执行程序+说明+详细注释.zip
- pta题库答案c语言之复杂度1最大子列和问题.zip
- 三维装箱问题(Three-Dimensional Bin Packing Problem,3D-BPP)是一个经典的组合优化问题
- 以下是一些关于Linux线程同步的基本概念和方法.txt
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功