用node.js导出类

我有一个名为bob_test.spec.js的文件正在由jasmine-node运行的以下testing代码

 require('./bob'); describe("Bob", function() { var bob = new Bob(); it("stating something", function() { var result = bob.hey('Tom-ay-to, tom-aaaah-to.'); expect(result).toEqual('Whatever'); }); }); 

为了使testing通过,我写了一个名为bob.js的文件,下面的生产代码

 "use strict"; var Bob = function() { } Bob.prototype.hey = function (text) { return "Whatever"; } module.exports = Bob; 

当我运行testing – 使用jasmine-node . – 我得到以下的F

 Failures: 1) Bob encountered a declaration exception Message: ReferenceError: Bob is not defined Stacktrace: ReferenceError: Bob is not defined at null.<anonymous> (/Users/matt/Code/oss/deliberate-practice/exercism/javascript/bob/bob_test.spec.js:4:17) at Object.<anonymous> (/Users/matt/Code/oss/deliberate-practice/exercism/javascript/bob/bob_test.spec.js:3:1) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.require (module.js:364:17) at require (module.js:380:17) Finished in 0.02 seconds 1 test, 1 assertion, 1 failure, 0 skipped 

基于我对Javascript的理解,我觉得这应该工作。 什么是node.js做不同的构造函数和模块出口,阻止这个工作我喜欢认为它应该?

需要返回一个对象,你应该把它存储在某个地方

 var Bob = require('./bob'); 

然后使用这个对象

 var bobInstance = new Bob(); 

这应该可以解决您在通过jasmine-node运行testing时遇到的错误:

 // Generated by CoffeeScript 1.6.2 (function() { var Bob; Bob = (function() { function Bob() {} Bob.prototype.hey = function(what) { return 'Whatever.'; }; return Bob; })(); module.exports = Bob; }).call(this); 

提高马文的答案:

 "use strict"; var Bob = function() {} Bob.prototype.hey = function (text) { return "Whatever"; } module.exports = new Bob(); // another file var Bob = require('./bob'); Bob.hey('text'); 

所以你可以创build一个对象传递给module.exports module.exports = new Bob();