我正在尝试了解如何开发独立的 Javascript 代码。我想编写带有测试和模块的 Javscript 代码,从命令行运行。所以我安装了 node.js
和 npm
以及库 requirejs
、underscore
和 mocha
.
我的目录结构如下:
> tree .
.
├── node_modules
├── src
│ └── utils.js
└── test
└── utils.js
其中 src/utils.js
是我正在编写的一个小模块,代码如下:
> cat src/utils.js
define(['underscore'], function () {
"use strict";
if ('function' !== typeof Object.beget) {
Object.beget = function (o) {
var f = function () {
};
f.prototype = o;
return new f();
};
}
});
和 test/utils.js
是测试:
> cat test/utils.js
var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});
requirejs(['../src/utils'], function(utils) {
suite('utils', function() {
test('should always work', function() {
assert.equal(1, 1);
})
})
});
然后我尝试从顶级目录运行(所以 mocha
看到 test
目录):
> mocha
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Calling node's require("../src/utils") failed with error: ReferenceError: define is not defined
at /.../node_modules/requirejs/bin/r.js:2276:27
at Function.execCb (/.../node_modules/requirejs/bin/r.js:1872:25)
at execManager (/.../node_modules/requirejs/bin/r.js:541:31)
...
所以我的问题是:
- 这是构建代码的正确方法吗?
- 为什么我的测试没有运行?
- 学习这类东西的最佳方法是什么?我很难在 Google 上找到好的示例。
谢谢...
[抱歉 - 暂时发布了错误代码的结果;已修复]
PS 我使用 requirejs 是因为我还想稍后从浏览器运行这段代码(或其中的一部分)。
更新/解决方案
下面的答案中没有的东西是我需要使用 mocha -u tdd
作为上面的测试样式。这是最终测试(也需要断言)及其用途:
> cat test/utils.js
var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});
requirejs(['../src/utils', 'assert'], function(utils, assert) {
suite('utils', function() {
test('should always work', function() {
assert.equal(1, 1);
})
})
});
> mocha -u tdd
.
✔ 1 tests complete (1ms)
最佳答案
您的测试未运行的原因是 src/utils.js
不是有效的 Node.js 库。
根据 RequireJS 文档,为了与 Node.js 和 CommonJS 要求标准共存,您需要 add a bit of boilerplate到 src/utils.js
文件的顶部,以便加载 RequireJS 的 define
函数。
但是,由于 RequireJS 被设计为能够要求“经典”面向 Web 浏览器的源代码,我倾向于将以下模式与我也希望在浏览器中运行的 Node.js 库一起使用:
if(typeof require != 'undefined') {
// Require server-side-specific modules
}
// Insert code here
if(typeof module != 'undefined') {
module.exports = whateverImExporting;
}
这具有不需要其他 Node.js 用户额外库的优点,并且通常与客户端上的 RequireJS 配合使用。
一旦您的代码在 Node.js 中运行,您就可以开始测试了。我个人仍然更喜欢 expresso 而不是 mocha,尽管它是后续测试框架。
关于javascript - 为什么在使用 RequireJS 运行 Mocha 测试时会看到 "define not defined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9303945/