2014-03-24 51 views
0

我有我在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; 

我需要能够通过出口这个,所以我可以在摩卡测试要求。但我也想让这个类在浏览器中实例化。

截至目前,我可以加载到浏览器,实例化它,这是很好的去。 (很明显,我在控制台得到一个错误约不理解的关键字是“出口”或“模块”)使用

exports.someFunction = function(args){}; 

但现在,我只想导出一个

通常我出口多个单功能函数,我没有通过原型链添加的方法被定义。

我试过module.exports,但似乎也没有办法。我的摩卡规范要求这样的文件:

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 

}); 

它看起来像我之前在摩卡是它被绊倒。我可以在实际的spec中实例化类,它工作得很好。

+1

你可以试试我的答案吗?我认为你需要在每个父母描述之前加以说明。我的答案详情。 – aiapatag

回答

1

关于mochajs,您需要将您的beforeEach置于父母describe的内部,并在子女describe s上有您的特定场景。否则,在beforeEach中完成的任务不会被您的describe识别。你的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 
    }); 
}); 

你可以看一下它的documentation进一步的细节。

+0

完全流感。谢谢你指点我正确的方向! –

+0

我说得太快了。无论我放在哪里,beforeEach平板都不起作用。但说实话,这个问题现在超出了原始问题的范围。我会谷歌一点,如果我无法修复它,我会发布一个完全不同的问题。 –

+0

嗯,这很奇怪。当然,我也对你面临的问题感兴趣。 – aiapatag