大家好,我是 JavaScript 的新手,正在使用 Quint 框架对我的函数进行单元测试。但是我遇到了一个问题,需要专家的帮助
这是我的问题
我有一个像这样的名为 calc.js 的文件
var calc; // global variable
(function(){
calc = (function(){
function calc(container, options) {
this._container = container;
this._jq_container = $(container);
this._options = options || {};
this.setupDefaults();
}
calc.prototype.setupDefaults = function() {
var _self = this;
_self._options.type = _self._options.type ? _self._options.type : 'add';
};
calc.prototype.add = function (val1, val2) {
return val1 + val2;
};
calc.prototype.sub = function (val1, val2) {
return val1 - val2;
};
return calc;
})();
$.fn.calc = function(options){
this.each(function(){
return new calc(this, options);
});
};
})();
现在我有一个类似这样的 qunit 的 html 文件
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<link rel="stylesheet" href="qunit/qunit.css">
<script src="qunit/qunit.js"></script>
<script src="http://code.jquery.com/jquery-1.7.2.js" type="text/javascript"></script>
<script type="test/javascript" src="calc.js"></script>
<script>
$(document).ready(function(){
test('add function test', function() {
equal(calc.add(2,4),"6" ,"function working correctly");
/*I have also tried to access add function using some other method but alway got an error*/
});
});
</script>
</head>
<body>
<h1 id="qunit-header">QUnit Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
</body>
</html>
我的 html 和 calc.js 都在同一个文件中 当我运行这个文件时,我得到了一个错误,没有定义 calc
我不明白为什么要将 calc 设为全局。
我也尝试过使用 window.calc = calc
但都是徒劳的
谁能指导我如何在我的 html 测试文件中访问这些功能
任何帮助将不胜感激
最佳答案
我在 jsfiddle.net 中运行了您的代码块,但您对 calc.add(2,4);
的函数调用没有运行。
我将调用更改为 calc.prototype.add(2,4)
并且我可以按预期调用您的函数。我建议您将 .prototype
添加到您的 QUnit 测试中?
关于javascript - Qunit 不可见的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11625233/