用React.addons.TestUtils、Jasmine进行单元测试

一、用到的工具

1.React.addons.TestUtils

2.Jasmine

3.Browserify(处理jsx文件的require依赖关系)

4.Reactify(能和browserify很好的配合,把jsx转换为js)

5.编译命令为 browserify -t reactify test.jsx > app.js (参数t为transform)

 

二、测试代码:

1.test.jsx

 1 var React = require("react/addons");
 2 var TestUtils = React.addons.TestUtils;
 3 var CheckboxWithLabel = require("./CheckboxWithLabel.jsx");
 4 
 5 describe("test CheckboxWithLabel component", function () {
 6     it("check label text", function () {
 7         var checkbox = TestUtils.renderIntoDocument(<CheckboxWithLabel text="你是否爱吃橘子" on="爱吃" off="不爱吃"></CheckboxWithLabel>);
 8         var text = React.findDOMNode(checkbox).textContent;
 9         expect(text).toContain("你是否爱吃橘子1");
10     })
11 })

2.CheckboxWithLabel.jsx

 1 var React = require('react/addons');
 2 var CheckboxWithLabel = React.createClass({
 3     getInitialState: function () {
 4         return {
 5             checked: false
 6         }
 7     },
 8     onChange: function() {
 9         this.setState({
10             checked: !!this.state.checked
11         });
12     },
13     render: function() {
14         return (
15             <label>
16                 {this.props.text}
17                 <input type = "checkbox" checked={this.state.checked} onChange={this.onChange}/> 
18                 {this.checked ? this.props.on : this.props.off} 
19             </label>);
20     }
21 });
22 
23 module.exports = CheckboxWithLabel;

3.index.html

 1 <!DOCTYPE html>
 2 <html lang="zh-cn">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>测试</title>
 6 </head>
 7 <body>
 8     <link rel="stylesheet" href="./node_modules/jasmine.css">
 9     <script src="./node_modules/jasmine.js"></script>
10     <script src="./node_modules/jasmine-html.js"></script>
11     <script src="./node_modules/boot.js"></script>
12     <script src="./app.js"></script>
13 </body>
14 </html>

 

三、运行结果

1.

2.若修改测试代码为expect(text).toContain("你是否爱吃橘子1"),则如下:

posted @ 2015-12-24 21:50  shamgod  阅读(1198)  评论(0编辑  收藏  举报
haha