• 用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"),则如下:

  • 相关阅读:
    MySQL的字符编码体系(一)——数据存储编码
    poj 1659 Frogs&#39; Neighborhood 度序列可图化 贪心
    POJ 1083 &amp;&amp; HDU 1050 Moving Tables (贪心)
    cocos2d-x wp8 中文显示问题
    Linux多线程编程
    how tomcat works 五 servlet容器 上
    SecureCRT 选择Courier New等其他字体.
    如何设置secureCRT的鼠标右键为弹出文本操作菜单功能
    SecureCRT中文显示乱码
    ZooKeepr日志清理
  • 原文地址:https://www.cnblogs.com/shamgod/p/5074430.html
Copyright © 2020-2023  润新知