您的位置:首页 > Web前端 > React

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

2015-12-24 21:50 537 查看
一、用到的工具

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

var React = require("react/addons");
var TestUtils = React.addons.TestUtils;
var CheckboxWithLabel = require("./CheckboxWithLabel.jsx");

describe("test CheckboxWithLabel component", function () {
it("check label text", function () {
var checkbox = TestUtils.renderIntoDocument(<CheckboxWithLabel text="你是否爱吃橘子" on="爱吃" off="不爱吃"></CheckboxWithLabel>);
var text = React.findDOMNode(checkbox).textContent;
expect(text).toContain("你是否爱吃橘子1");
})
})


2.CheckboxWithLabel.jsx

var React = require('react/addons');
var CheckboxWithLabel = React.createClass({
getInitialState: function () {
return {
checked: false
}
},
onChange: function() {
this.setState({
checked: !!this.state.checked
});
},
render: function() {
return (
<label>
{this.props.text}
<input type = "checkbox" checked={this.state.checked} onChange={this.onChange}/>
{this.checked ? this.props.on : this.props.off}
</label>);
}
});

module.exports = CheckboxWithLabel;


3.index.html

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<link rel="stylesheet" href="./node_modules/jasmine.css">
<script src="./node_modules/jasmine.js"></script>
<script src="./node_modules/jasmine-html.js"></script>
<script src="./node_modules/boot.js"></script>
<script src="./app.js"></script>
</body>
</html>


三、运行结果

1.



2.若修改测试代码为expect(text).toContain("你是否爱吃橘子1"),则如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: