简体   繁体   中英

Export function/class from node.js module

I have a class that I've defined in Javascript like this:

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;

I need to be able to export this so I can test it in Mocha by using require. But I'd also like to still allow this class to be instantiated in the browser.

As of now, I can load this into a browser, instantiate it and it's good to go. (Obviously I get an error in the console about not understanding the keyword 'export' or 'module')

Typically I export multiple single functions using

exports.someFunction = function(args){};

But now that I want to just export that one function, none of the methods that I've added via the prototype chain are defined.

I've tried module.exports but that doesn't seem to do the trick either. My Mocha spec requires the file like this:

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

});

It looks like my beforeEach in Mocha is where it gets tripped up. I can instantiate the class in the actual spec, and it works just fine.

On mochajs, you need to put your beforeEach inside a parent describe , and have your specific scenarios on children describe s. Else, things done in beforeEach doesn't get recognized by your describe . Your myCoolClass is just treated as a global variable and nothing was really instantiated, that's why the prototype functions are undefined.

So it's somewhat like (sorry I'm just on mobile):

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
   });
});

You can look at its documentation for further details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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