QUnit是用来测试javascript真确性的,是一个简单强大的单元测试框架。如果你已经熟悉javascript,那么上手QUnit的难度几乎为0。

QUnit编写测试非常的简简明了。

测试函数:

1
2
3
test('测试名称', function() {
// 代码
});

简单上手

创建一个html文件,载入QUnit的的css、javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>QUnit Example</title>
<link rel="stylesheet" href="/resources/qunit.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="/resources/qunit.js"></script>
<!-- 编写的测试文件 -->
<script src="/resources/tests.js"></script>
</body>
</html>

简单的一个测试:

1
2
3
test( "hello QUnit", function() {
ok( 1 == "1", "通过" );
});

断言(asserts)

只是测试本身是没有多大用处的。主要是为了调用一些代码来断言该代码的正确性。我们所做的唯一的事情是确保代码执行,但是其正确性仍然是一个未知的问题。

这时候断言的作用就表现出来了。QUnit 断言方法:

简单的断言例子:

1
2
3
test( "test assert", function() {
notStrictEqual( 1 === "1", "通过" );
});

模块(modules)

modules通常是用来分组管理测试的,模块内的信息是共享的。一个模块是从模块声明开始一直到下一个模块申明结束。

简单代码:

1
2
3
4
module('模块名称');
test( "测试名称", function() {
strictEqual( 1 === 1, "通过" );
});

setup 和 teardown 函数

除了分组测试,模块的另一目的是组织相关测试数据。当指定一个setup 或者 teardown函数时 ,这些功能将每个测试模块内运行。

所以,可以使用一个模块来测试有相同设置的数据。

代码类似:

1
2
3
4
5
6
7
8
module('模块名称', {
setup: function() {
// setup code
},
teardown: function() {
// teardown code
}
);

与requirejs集成问题

QUnit与requirejs集成有一点问题,但是非常好解决。

因为QUnit默认是自动开始的所以使用的时候先设置为关闭,然后再加载模块完成后再执行。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
require.config({
// 增加时间值 防止缓存
urlArgs:"v=" + (new Date()).getTime(),
paths:{
QUnit:'qunit/qunit/qunit'
},
shim: {
'QUnit': {
exports: 'QUnit',
init: function() {
// QUnit.config.autoload = false;
QUnit.config.autostart = false;
}
}
}
});
require([
'QUnit',
'./unit/core'
],function(QUnit){
// run the tests.
// 依次调用run方法
for(var i = arguments.length-1 ; i > 0 ; i-- ){
arguments[i].run();
}
// start QUnit.
QUnit.load();
QUnit.start();
});

为了满足上面编写,测试模块基本结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
define([
'core',
],function(core){
var run = function() {
module("core");
test("测试 ", function () {
});
};
return {run: run}
});

参考文档