Javascript 如何以编程方式将html注入qunit fixture
我想通过编程将html注入到qunit fixture中进行测试。我尝试过使用$.load,但是处理HTML的JS在加载HTML之前就被执行了 HTML:Javascript 如何以编程方式将html注入qunit fixture,javascript,requirejs,qunit,Javascript,Requirejs,Qunit,我想通过编程将html注入到qunit fixture中进行测试。我尝试过使用$.load,但是处理HTML的JS在加载HTML之前就被执行了 HTML: <div id="qunit"></div> <div id="qunit-fixture"></div> <script src="../components/bower/qunit/qunit/qunit.js"></script> <script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="../components/bower/qunit/qunit/qunit.js"></script>
<script>
QUnit.config.autostart = false;
</script>
<script data-main="tests" src="../components/bower/requirejs/require.js"></script>
还有我的测试:
define(['foo'], function(foo) {
'use strict';
var Test = {
test: function() {
module( "module Foo");
asyncTest("foo class test", function() {
expect(1);
// foo() is executed before load is done :(
$('#qunit-fixture').load('../components/app/foo/foo.html', function(data) {
ok($('.foo').hasClass('testit'), ".foo should have class 'testit'");
QUnit.start();
});
});
}
};
return {
test: Test.test
};
});
因为内容的加载是异步的,所以您需要。请注意,这只是猜测您的测试线束可能会是什么样子,它可能需要针对您的用例进行更新
<!-- in your test HTML document -->
<script>
QUnit.config.autostart = false;
// your code to load the HTML dynamically in the fixture
// your test definitions
require(
[ "src/yourSourceCode", "tests/theTests" ],
function() {
QUnit.start(); // this starts the main QUnit code
}
);
</script>
现在,在测试中,您可以执行以下操作:
define(['foo'], function(foo) {
'use strict';
var Test = {
test: function() {
module( "module Foo");
asyncTest("foo class test", function() {
expect(1);
$('#qunit-fixture').load('../components/app/foo/foo.html', function(data) {
foo.init(); // we've moved the initialization to here...
ok($('.foo').hasClass('testit'), ".foo should have class 'testit'");
QUnit.start();
});
});
}
};
return {
test: Test.test
};
});
我将HTML添加到原始问题中。在那里你可以看到我已经阻止了qunit自动启动。问题不是测试运行需要加载模块。但是加载的模块在测试将HTML插入到qunit fixtureAaah之前启动。。。我懂了。这里的问题是调用
Foo.\u init()在模块中立即使用代码>方法。我将更新此答案,以演示如何绕过此问题。这当然可以消除问题。但是我不想改变我的应用程序的逻辑来让测试正常工作。或者这就是测试优先范式的本质?我觉得仅仅为了测试而公开私有函数是不对的。嗯。。。我想这是一个方法论问题。我认为模块范式并不要求模块自行启动。事实上,在大多数情况下,我总是为我的模块导出某种“启动”方法。也许这个模块不会在任何其他上下文中使用,但是考虑它是否是…是否会预先设置其他上下文?如果它是一个具有动态内容的SPA呢?在任何情况下,如果您想动态加载内容,那么您必须以某种方式延迟模块代码的执行。感谢您就此事分享不同的观点,听取其他意见总是有帮助的:)
define(['jquery'], function($) {
'use strict';
var Foo = {
_init: function() {
...
},
...
};
// Foo._init(); // don't do this here...
return {
greet : Foo.greet,
init : Foo._init // add the init method to your exports
};
});
define(['foo'], function(foo) {
'use strict';
var Test = {
test: function() {
module( "module Foo");
asyncTest("foo class test", function() {
expect(1);
$('#qunit-fixture').load('../components/app/foo/foo.html', function(data) {
foo.init(); // we've moved the initialization to here...
ok($('.foo').hasClass('testit'), ".foo should have class 'testit'");
QUnit.start();
});
});
}
};
return {
test: Test.test
};
});