java script测试之js unit ut
TRANSCRIPT
JavaScript Testing 之JSUnit UT
CBU- 技术部 - 商业产品开发部 -前端组
Agenda:
• 什么是 UT• 前端为什么需要 UT• UT 的基础• UT 的框架选型• 怎么写 UT• 我们遇到的问题及如何解决的• QA
30mins+
什么是 UT?
A
BC
3 步• Set Up• Prepare an input • Call a method • Check an output• Tear down
t.test_methodA=function(){ var input={some input value}; var output=A(input); jsunit.assertEquals(output,expectValue);}
A unit test is a piece of a code (usually a method) that invokes another piece of code and checks the correctness of some assumptions afterward.
If the assumptions turn out to be wrong, the unit test has failed.
A “unit” is a method or function. UT should be : Automated, trustworthy,
readable, and maintainable.
前端为什么需要 UT?
前端逻辑复杂化 设备多样化 / 前端环境复杂化 前端开发模块化 前端组件重用化
减少 Bug 数目,提高前端的代码质量,
规范前端编码
单元测试元素的组成 ✦ Test Suite
✦ Tests ✦ Assertions
✦ Async Tests
✦ Test Runner
Assertions
✦assert([comment], booleanValue) ✦ assertTrue([comment], booleanValue) ✦ assertFalse([comment], booleanValue) ✦ assertEquals([comment], value1, value2) ✦ assertNotEquals([comment], value1, value2) ✦ assertNull([comment], value) ✦ assertNotNull([comment], value)
…• More http://www.jsunit.net/documentation/
Tests
t.testEval3 =function(){ jsunit.assertEquals(4, eval("2 + 3")); };
t.testEval4 = function() { var a=function(){}; jsunit.assertTypeOf(a, "function");
};
TestRunner
UT 框架的选择
JSUnit QUnit …
JSunit VS QUnitJSUnit QUnit
运行是否方便 不太方便,需要运行testRunner
很方便,写完,刷新,即可运行
语法风格 还是 2000 年时候的,有点过时
比较语义化 , 有 module的概念
是否支持异步 不支持,需要使用setTimeOut 等来解决
支持,使用 start ,stop 等
是否支持 Ant 支持 不支持
是否可以 CI 可以, Hudson 有现成的插件
不支持,输出的结果带html 标签, john 设计时就没考虑这个
是否适合大型或多个项目 比较适合,有 testsuit 和testpage 概念
多个项目,有点混乱
远程控制 支持 不支持
为什么选择 JSUnit
• JSUnit 设计理念源于 Junit, 后端的开发同学容易接受
• Ant, CI, 多项目的支持
语法改造• Ali.test.jsunit.defineTests("ali.ux.logging", function(t,
jsunit) { jsunit.require("logger/js/logging.js"); t._setUp = function() { //todo }; t._tearDown = function() { //todo };
• } );
异步支持
t.testAsyncCall=function(){ jQuery.ajax({
url: jsunit.TEST_BASE+"wxb/data/data.json", success:t.asyncCallback(function(obj){ jsunit.assertEquals(1,obj.data.userType); }),
dataType: "json"
});
}; t.testAsyncCall._async=true;
怎样写?
Demo
问题列表前端单元测试能带给我们什么?
1 : 产品的功能性描述2 : API 的浏览器兼容性测试3 : 重要 bug 的 fix 测试4 : 添加新功能,是否影响老功能的测试5 : 产品的可维护性更好
在编写代码过程过,对于可测性,有个很重要的问题,就是有的私有函数,为了安全性,用闭包来封装,断绝其和外界的访问,但这就给可测性带来了问题。
方案: 在编写代码时,需要测试的方法,我们可以使用 _testName 来定义其为私有函数,然后使用 @aliobf-clobber 等这些meta-data 来描述,类似于 Google guice 的方式。使用 ant 和 Java 方式来解决。
什么样的项目适合做单元测试? ✦ 需要 JS 处理业务逻辑 (Heavy JavaScript APP ) ✦ 后台拿到数据后,需要对数据进行处理的 ✦ 前端面向对象编程,而且最好 logic 和view 是分开的。
什么样的项目不适合做单元测试? 单纯的从后端拿到数据,然后显示的项目
QA