我正在编写一个node.js 模块,并且我的模块有一个私有(private)类。
我正在尝试针对此类编写测试,但不知道如何做到这一点。
我的模块看起来像这样
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
然后在我的规范文件夹中我有
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); }) });
我猜他们是我在规范中创建新类的一种方法,但我不确定如何或如何导出该类。
最佳答案
使用您当前正在做的事情,您必须拥有
module.exports = { main: main, MyClass: MyClass }
然后在规范中使用 new mymodule.MyClass
来实例化您的类。不过,这意味着您的类(class)的“常规”用户必须执行 mymodule.main("Item")
而不是 mymodule("Item")
,这更改模块的原始接口(interface)。
我不知道我要建议的是模式还是反模式,但这是解决它的一种方法:
module.exports = main;
module.exports.MyClass = MyClass; // only if testing
这是,您的模块对普通用户的接口(interface)保持不变,并且您的规范可以使用 new mymodule.MyClass()
创建该类的实例。
关于node.js - 测试模块中的 node.js 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556928/