簡體   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