TL;DR
使用开箱即用的qunit 命令(预先执行npm install -g qunit),因此您不需要额外的依赖项。
扩展一点 Arthur 的答案,因为他只提到了仅适用于最简单项目的最简单案例。
正如QUnit 页面上所提到的,内置了从命令行运行测试的可能性。 无需在 QUnit 之上安装额外的奇怪框架!
npm install -g qunit
qunit # Will search for tests in "test" directory
这适用于他们网站上的人工测试,但在实际项目中,您可能会将您的逻辑放在其他一些 .js 文件中。
结构如下:
project
│ index.js <--- Your script with logic
│ package.json <--- most probably you'll have npm file since qunit executable is installed via npm
└───test
tests.html <--- QUnit tests included in standard HTML page for "running" locally
tests.js <--- QUnit test code
让我们想象一下,在您的 index.js 中,您有以下内容:
function doSomething(arg) {
// do smth
return arg;
}
还有tests.js中的测试代码(不是说它可以是文件的整个内容——你不需要其他任何东西来工作):
QUnit.test( "test something", function( assert ) {
assert.ok(doSomething(true));
});
在浏览器中运行
这与问题没有直接关系,只是想在这里做一个参考。
只需将您的脚本和测试都放入 tests.html 并在浏览器中打开页面:
<script type="text/javascript" src="../index.js"></script>
<script src="tests.js"></script>
从命令行运行
使用下面描述的设置,您可以尝试运行qunit,但它不会工作,因为它找不到您的函数doSomething。要使其可访问,您需要在脚本中添加两件事。
首先是从测试中明确“导入”您的脚本。由于 JS 没有开箱即用的功能,我们需要使用来自 NPM 的require。为了让我们的测试在 HTML 中运行(当您从浏览器运行它时,require 未定义)添加简单检查:
// Add this in the beginning of tests.js
// Use "require" only if run from command line
if (typeof(require) !== 'undefined') {
// It's important to define it with the very same name in order to have both browser and CLI runs working with the same test code
doSomething = require('../index.js').doSomething;
}
但如果index.js 不公开任何内容,则将无法访问任何内容。因此,需要显式公开您想要测试的函数(阅读更多关于exports 的信息)。将此添加到 index.js:
//This goes to the very bottom of index.js
if (typeof module !== 'undefined' && module.exports) {
exports.doSomething = doSomething;
}
完成后,首先检查 tests.html 是否仍在工作并且没有引发任何错误(测试测试基础设施,是的),最后尝试
qunit
输出应该是这样的
TAP version 13
ok 1 Testing index.js > returnTrue returns true
1..1
# pass 1
# skip 0
# todo 0
# fail 0
我不想为我的简单(或不)项目处理节点
这是一个悬而未决的问题,我无法回答。但是无论如何,您都需要 一些 runner 来运行 QUnit 测试。所以也许拥有package.json 和一个像"qunit": "^2.6.1" 这样的devDependency 并不是最糟糕的选择。有几个3rd-party runner:grunt-qunit,PhantomJS runnner,ember-qunit-cli,也可以在官方QUnit Plugins page查看更多
如果我有课而不是功能怎么办?
在 JS 中一切都是函数,对吧 :)?所以没问题,只需相应地更改您的脚本导出和测试导入
exports.exportedMyClass = MyClass; // in index.js
MyClass= require('../index.js').exportedMyClass ; // in tests.js
参见示例,也称为小型入门 here。