我正在使用QUnit与require.js一起对backbone.js应用程序进行单元测试。所有测试都是异步的,使用asyncTest
方法。
我正在使用setup
和teardown
来构建并删除每个测试的工具。我的问题是虽然asyncTest
似乎是阻塞的,但setup()
在每个测试开始之前都会被调用,几乎所有setup()
个调用都会同时运行。 This solution似乎无法解决我的问题。下面我有一个如何设置模块的示例,这里是test repository that illustrates the problem
我的问题是:我做错了什么还是这个QUnit的正常行为?
module('Module', {
setup: function(){
console.log('setup');
},
teardown: function(){
console.log('teardown');
}
})
asyncTest('Test 1', function() {
setTimeout(function(){
equal(2, 2, 'The return should be 2.');
start();
}, 400);
});
asyncTest('Test 2', function() {
setTimeout(function(){
equal(1, 1, 'The return should be 1.');
start();
}, 400);
});
答案 0 :(得分:6)
QUnit期望一个相当具体的页面加载行为。通过requirejs加载它可能看起来有效,但实际上并没有。建议通过常规脚本标记加载QUnit。只要你设置QUnit.config.autostart = false
,就可以通过requirejs加载测试本身。
答案 1 :(得分:0)
包含解决方案Jörn Zaefferer的Blogpost指定above - http://www.jonnyreeves.co.uk/2012/qunit-and-requirejs/
这是我实施的内容 -
我遇到的问题:
我通过require包含了qunit。这似乎适用于所有同步测试。我在我的qunit模块的设置中定义了一个变量,并在拆卸时返回null。当我包含一个asyncTest时,它似乎没有被拆卸正确地重置,因此打破了那个预期新变量之后运行的所有测试。
关键点
它可能不是最优雅的,但我也没有碰到任何端到端的例子,我只是烧了几个小时找到这个答案(因为我第一次认为我正在设置我的asyncTest错误)。 / p>
<link rel="stylesheet" href="qunit-1.12.0.css">
<script type="text/javascript" src="qunit-1.12.0.js"></script>
<script>
QUnit.config.autostart = false
require(['App'],
function(){
//Modules that have been loaded in by require.js
var loadedModules = [];
//Locations of test modules to load
var moduleLocations = [
'tests/test1',
'tests/test2',
'tests/test3'
];
//If all modules have been loaded, run them
function runTests(){
if (loadedModules.length == moduleLocations.length){
QUnit.start();
_.each(loadedModules,function(test){
test();
});
}
}
_.each(moduleLocations,function(string){
require([string],
function(a){
loadedModules.push(a);
runTests();
});
});
});
</script>
单独的测试模块文件:
define(['array','of','test','requirements'], function() {
return function(){
var options = null;
module('Autocomplete',{
setup: function() {
// prepare something for all following tests
options = new whatever();
},
teardown: function() {
// clean up after each test
options = null;
}
});
test( "normal tests", function() {
ok(true,"normal assertions");
});
}
});