我刚刚开始使用 Qunit,想知道是否有办法捕获/验证/忽略警报,例如:
function to_test() {
alert("I'm displaying an alert");
return 42;
}
然后有类似的东西:
test("to_test", function() {
//in this case I'd like to test the alert.
alerts("I'm displaying an alert", to_test(), "to_test() should display an alert");
equals(42, to_test(), "to_test() should return 42" ); // in this case I'd like to omit the alert
});
我也愿意接受使用另一个单元测试工具的建议。
提前致谢!
好吧,看起来像Sinon.JS http://sinonjs.org/docs/#stubs就是您正在寻找的。我以前从未使用过它,但我确实回答过你的问题。
您可以将全局函数alert(实际上是window.alert)替换为一个临时函数,该函数将记录本来要显示的消息。
用 javascript 很容易做到(window.alert = function(msg) { savedMsg = msg; })
。所以你可以在测试中做到这一点。
复杂性仅来自于运行测试后的清理工作。这就是你需要的地方Sinon.JS http://sinonjs.org/docs/#stubs哪个行与 QUnit 集成 http://cjohansen.no/en/javascript/using_sinon_js_with_qunit。你需要这个集成脚本 http://sinonjs.org/releases/sinon-qunit-0.8.0.js.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
<script type="text/javascript" src="sinon-1.1.1.js"></script>
<script type="text/javascript" src="sinon-qunit-0.8.0.js"></script>
<script>
function to_test() {
window.alert("I'm displaying an alert");
return 42;
}
$(document).ready(function(){
module("Module A");
test("first skip alert test ", function() {
var stub = this.stub(window, "alert", function(msg) { return false; } );
equals(42, to_test(), "to_test() should return 42" );
equals(1, stub.callCount, "to_test() should have invoked alert one time");
equals("I'm displaying an alert",stub.getCall(0).args[0], "to_test() should have displayed an alert" );
});
});
</script>
</head>
<body>
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)