javascript的调试问题,是每个网页开发人员头疼的事情,火狐插件 firebug虽然解决了很多事情,但是当js文件越来越大的时候,对js的管理变成了越来越棘手的事情。

我们大家都知道对C#的单元测试有一个非常好用的工具 - Nunit,那么有没有一个类似的工具,对javascript代码进行单元测试? 答案是有的,它就是QUnit.

 

下面用一个简单的实例讲解QUnit的操作步骤:

 

第1步.  在html文件中加入头部引用

 

<link rel="stylesheet" href="css/qunit.css" type="text/css" media="screen" /> 
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<script type="text/javascript" src="js/qunit.js"></script>

 

 

 

第2步. 编写Html代码

1  <h1 id="qunit-header">第一个QUnit的例子</h1>  

2  <h2 id="qunit-banner"></h2>
3  <div id="qunit-testrunner-toolbar"></div>
4  <h2 id="qunit-userAgent"></h2>
5  <ol id="qunit-tests"></ol>
6  <div id="qunit-fixture">test markup, will be hidden</div>

 

第3步. 编写javascript代码

 1 <script>
 2   $(document).ready(function(){
 3     
 4 test("a basic test example", function() {
 5   ok( true, "this test is fine" );
 6   var value = "hello";
 7   equal( value, "hello", "We expect value to be hello" );
 8 });
 9 
10 module("Module A");
11 
12 test("first test within module", function() {
13   ok( true, "all pass" );
14 });
15 
16 test("second test within module", function() {
17   ok( true, "all pass" );
18 });
19 
20 module("Module B");
21 
22 test("some other test", function() {
23   expect(2);
24   equal( truefalse, "failing test" );
25   equal( truetrue, "passing test" );
26 });
27 
28   });

29   </script>  



第4步. 点击运行Html文件,查看测试结果

 

  使用QUnit对javascript脚本进行单元测试

 

 从上图可以明显的看出,第4个模块的第一个方法有问题,期望返回值是false,但是返回了true。

 

最后总结一下,对javascript代码的单元测试跟C#单元测试非常类似,使用jquery插件QUnit进行单元测试,帮我们节省了不少脚本调试的时间。

参考资料见官方网站:http://docs.jquery.com/QUnit  

补充一下,我负责开发的网站十里路采用了大量的QUnit测试方法,大大提高了开发效率。
  

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
  • 2021-07-04
  • 2022-12-23
  • 2021-12-03
  • 2021-11-11
  • 2021-07-30
猜你喜欢
  • 2021-10-15
  • 2022-03-05
  • 2021-12-14
  • 2021-08-30
  • 2021-09-01
  • 2022-12-23
  • 2022-02-16
相关资源
相似解决方案