繁体   English   中英

从node.js模块导出函数/类

[英]Export function/class from node.js module

我有一个用Javascript定义的类,如下所示:

var CoolClass = function() {
  this.prop1 = 'cool';
  this.prop2 = 'neato';
}

CoolClass.prototype.doCoolThings = function(arg1, arg2) {
  console.log(arg1 + ' is pretty ' + this.prop1;
}

modules.export = CoolClass;

我需要能够导出它,以便可以通过使用require在Mocha中对其进行测试。 但我也想仍然允许在浏览器中实例化此类。

到目前为止,我可以将其加载到浏览器中,实例化它,并且很好。 (很明显,在控制台中由于不了解关键字'export'或'module'而出现错误)

通常我使用以下命令导出多个单个函数

exports.someFunction = function(args){};

但是现在我只想导出一个函数,所以没有定义通过原型链添加的方法。

我已经试过module.exports,但这似乎也不能解决问题。 我的Mocha规范要求使用以下文件:

var expect = require('chai').expect;
var coolClass = require('../cool-class.js');
var myCoolClass;

beforeEach(function() {
  myCoolClass = new coolClass();// looks like here is where the issue is
});

describe('CoolClass', function() {
  // if I instantiate the class here, it works.
  // the methods that were added to CoolClass are all undefined

});

看起来像我的beforeEach在Mocha中被绊倒了。 我可以在实际的规范中实例化该类,并且效果很好。

在mochajs上,您需要将beforeEach放在父describe ,并将子场景的特定场景describe 否则,您的describe不会识别在beforeEach中完成的事情。 您的myCoolClass仅被视为全局变量,并且没有真正实例化任何内容,这就是为什么原型函数未定义的原因。

所以有点像(对不起,我只是在移动设备上):

var MyCoolClass = require('mycoolclass.js');
describe('MyModule', function () {
  var myCoolClass;

  beforeEach(function () {
    myCoolClass = new MyCoolClass();
  });

  describe('My Scenario 1', function () {
    myCoolClass.doSomethingCool('This'); //or do an assert
   });
});

您可以查看其文档以获取更多详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM