【发布时间】:2018-06-13 06:15:51
【问题描述】:
作为一个 JavaScript 新手,我很难理解如何“加载”我的代码,以便我可以在应用程序之外使用单元测试对其进行测试。
在 PHP 中,我有一个自动加载器(composer),所以我可以引用我想要与之交互的类并自动加载它,或者我可以使用require_once 来包含一个物理文件和其中的类或函数文件可供我使用。
所以,其中一个类(存储在文件 src/lib/App/Calculator.js 中)...
App.Calculator = (function () {
var Calculator = function (onUpdateCallback) {
this.amountChange = 0.00;
this.amountDue = 0.00;
this.amountTendered = 0.00;
this.onUpdateCallback = onUpdateCallback;
};
Calculator.prototype = {
clear: function () {
this.amountTendered = 0.00;
this.calculate();
},
calculate: function () {
if (this.amountDue > 0) {
this.amountChange = Math.max(0, this.getAmountTendered() - this.amountDue);
} else {
this.amountChange = -(this.getAmountTendered() + this.amountDue);
}
if (typeof this.onUpdateCallback === 'function') {
this.onUpdateCallback(this);
}
},
getAmountTendered: function () {
return Number(this.amountTendered);
},
getChange: function () {
return this.amountChange;
},
setAmountTendered: function (amountTendered) {
this.amountTendered = parseFloat(amountTendered);
this.calculate();
},
setAmountDue: function (amountDue) {
this.amountDue = parseFloat(amountDue);
if (this.amountDue < 0) {
this.negative = true;
}
this.calculate();
}
};
return Calculator;
})();
我希望能够创建 App.Calculator 的新实例并在应用程序之外对其进行测试。从命令行。
从 PHPUnit 到 JS,我知道我缺少很多理解,所以任何指针(自以为是或其他)都将不胜感激。
【问题讨论】:
-
如果你只是在浏览器中打开你的网站,你应该可以访问
App.Calculator,然后做你想做的事。 -
在浏览器中打开你的应用程序 -> f12 -> 来源 -> 找到 js 文件并在你的类中放置任意数量的断点和重新加载页面或 f12 -> var calc = App.calculator (); calc.getChange(); ...无论您想在课堂上测试什么;
-
如果您正在寻找 JUnit 测试框架,我可以推荐 Facebook 的 Jest。我基本上随附电池,并且非常容易设置。
-
@RoumelisGeorge 这个问题是关于运行单元测试的。这与调试代码或在浏览器中手动测试无关。
-
我在我的 nodejs 项目中使用 mocha / chai。关于在这些测试中导入代码,我建议使用基于模块的方法,请参阅:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 如果代码打算在浏览器中运行,您可能必须使用像 babel 或 bundler 这样的转译器作为 webpack。