我正在尝试使用 Mocha 设置一些 JS 单元测试,理想情况下,我想通过与网页相反的命令行运行它。(TL:DR;在底部)
首先,我做了一些废话测试,以确认 Array 按预期工作,我直接从 Mocha 的页面http://visionmedia.github.io/mocha/#getting-started提取,并且按预期工作。
此时,为了提高赌注,我创建了一个新文件 /src/cow.js :
/** This example is taken from https://nicolas.perriault.net/code/2013/testing-frontend-javascript-code-using-mocha-chai-and-sinon/**/
(function(exports) {
"use strict";
function Cow(name) {
this.name = name || "Anon cow";
}
exports.Cow = Cow;
Cow.prototype = {
greets: function(target) {
if (!target)
throw new Error("missing target");
return this.name + " greets " + target;
}
};
})(this);
连同我的测试文件/test/test.js:
var chai = require("chai"),
expect = chai.expect;
require( "../src/cow.js");
describe( "Cow", function(){
describe( "constructor", function(){
it( "should have a default name", function(){
var cow = new Cow();
expect( cow.name).to.equal( "Anon cow");
});
it( "show use provided name", function(){
var name = "duck Cow",
cow = new Cow( name );
expect( cow.name).to.equal( name );
})
});
});
并运行“摩卡”。此时我收到以下错误:
1) Cow constructor should have a default name:
ReferenceError: Cow is not defined
at Context.<anonymous> (C:\Users\myUserName\\jsUnitTesting\helloWorld\test\test.js:10:27)
at Test.Runnable.run (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:211:32)
at Runner.runTest (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:358:10)
at C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:404:12
at next (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:284:14)
at C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:293:7
at next (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:237:23)
at Object._onImmediate (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:261:5)
at processImmediate [as _immediateCallback] (timers.js:330:15)
2) Cow constructor show use provided name:
ReferenceError: Cow is not defined
at Context.<anonymous> (C:\Users\myUserName\\jsUnitTesting\helloWorld\test\test.js:16:27)
at Test.Runnable.run (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:211:32)
at Runner.runTest (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:358:10)
at C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:404:12
at next (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:284:14)
at C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:293:7
at next (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:237:23)
at Object._onImmediate (C:\Users\myUserName\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:261:5)
at processImmediate [as _immediateCallback] (timers.js:330:15)
这显然不太理想。我认为这是因为 test.js 不知道 cow.js。如您所见,我使用了require,但这似乎不起作用。
TL:博士;
那么,将此文件(cow.js)添加到我的测试文件(test.js)中的正确方法是什么?目前,除了 mocha 和 nodeJS 之外,我没有使用任何库
谢谢!