我写了一个小页面来学习BDD/TDD。它在http://duolingo.howyousay.it/link.html上
我的测试(目前只有一个文件)在http://duolingo.howyousay.it/tests/test.html?coverage&hidepassed&noglobals
除了http://duolingo.howyousay.it/duolingo_link_fixer.js中的5行代码外,我已经设法获得了100%的代码覆盖率
1 var DuolingoLinkFixer = function() {
2 this.data = {};
3 var self = this;
4
5 document.onreadystatechange = function () {
* 6 self.init();
7 }
8 };
9
10 DuolingoLinkFixer.prototype.init = function() {
* 11 if (document.readyState == "complete") {
* 12 this.setOriginalUrl();
* 13 this.setAlternateText();
* 14 this.setFixedUrl();
15 }
16 }第6行和第11-14行没有经过测试,但是如果我删除它们,代码就不能工作。我使用的是QUnit、QUnit-BDD和Blanket.js。我如何测试在onready之前运行的部分代码,因为这些测试似乎只在onready之后开始运行
我的测试代码目前是这样开始的:
describe("DuolingoLinkFixer", function() {
describe("new", function() {
it("should create a new instance of DuolingoLinkFixer", function() {
expect(new DuolingoLinkFixer instanceof DuolingoLinkFixer).to.be.true();
});
});
});这是我的测试HTML页面的源代码:
<!DOCTYPE html>
<html>
<head>
<title>Duolingo JavaScript tests</title>
<script type="text/javascript" src="/lib/jquery/jquery-3.0.0.js"></script>
<script type="text/javascript">
$.holdReady(true);
</script>
<link type="text/css" rel="stylesheet" href="/lib/qunit/qunit-1.23.1.css">
<script type="text/javascript" src="/lib/qunit/qunit-1.23.1.js"></script>
<script type="text/javascript" src="/lib/qunit-bdd/qunit-bdd.js"></script>
<script type="text/javascript" src="/lib/blanket.js/blanket.min.js"></script>
<script type="text/javascript" data-cover src="../url_helper.js"></script>
<script type="text/javascript" data-cover src="../duolingo_link_fixer.js"></script>
<script type="text/javascript" src="test_url_helper.js"></script>
<script type="text/javascript" src="test_duolingo_link_fixer.js"></script>
</head>
<body>
<div id="qunit"></div>
</body>
</html>我试着按照另一篇文章中的建议添加了jQuery的$.holdReady(true);,但是没有帮助。我不需要使用jQuery,所以我在这个项目中尽量避免使用它。
发布于 2016-07-09 08:19:01
事实证明,我只需要在我的测试代码中添加一行代码来测试以前无法测试的代码:
describe("DuolingoLinkFixer", function() {
describe("new", function() {
it("should create a new instance of DuolingoLinkFixer", function() {
expect(new DuolingoLinkFixer instanceof DuolingoLinkFixer).to.be.true();
document.onreadystatechange();
});
});
});添加document.onreadystatechange();会运行代码,就像它是由readyStateChange事件触发一样。
https://stackoverflow.com/questions/37904608
复制相似问题