I'm writing a node.js module and my module has a private class.
I'm trying to write tests against this class, but can't figure out how to do that.
My module looks like this
var main = function(get_item){ var main_item = new MyClass(get_item); return main_item } function MyClass(item){ this.item = item; return this.init(); } MyClass.prototype = { init: function(){ return find_item(); }, find_item: function(){ // does a bunch of stuff to look up an item }, update_item: function(){ // does a bunch of stuff to update the item }, // a bunch more methods here } module.exports = main // probably turn on and off for testing module.exports = new MyClass //??? not sure how to do this
Then in my spec folder I've got
var main = require("./modules/myClass"); describe("get item",function(){ it("should return an item",function(){ var item_obj = main.get_item("first_item"); expect(item_obj.index).toBe(1); }) });
I'm guessing their is a way for me to create a new class in my spec, but I'm not sure how, or how to export the class.
Using what you are currently doing, you would have to have
module.exports = { main: main, MyClass: MyClass }
Then use new mymodule.MyClass
in your spec to instantiate your class. It would mean, though, that "regular" users of your class would have to do mymodule.main("Item")
instead of mymodule("Item")
, which changes the original interface of your module.
I have no idea if what I am about to suggest is a pattern or an anti-pattern, but here's one way to solve it:
module.exports = main;
module.exports.MyClass = MyClass; // only if testing
This was, your module's interface to regular users remains the same, and your spec can create an instance of the class by using new mymodule.MyClass()
.