[英]How to test pure JavaScript module with mocha.js
I'm trying to test simple frontend code. 我正在尝试测试简单的前端代码。 I just want to check with mocha that
myModule
is object
and keys length
greater then 0
. 我只想与mocha一起检查
myModule
是object
并且密钥length
大于0
。
Module definition: 模块定义:
var myModule = (function () {
return {
option: false
};
})();
I'm trying to do so: 我正在尝试这样做:
var expect = require('chai').expect;
var myModule = require('<path_to_my_moule_file>');
describe("myModule", function() {
it("is myModule object", function() {
expect(myModule).to.be.a('object');//I know it's not enough
});
it("is myModule not empty", function() {
expect(Object.keys(myModule)).to.have.length.greaterThan(0);
});
});
But of course this didn't work. 但是,当然这是行不通的。 Because my module isn't a nodejs module I thought, anyway
myModule
returns simple {}
, but not a real value of it (I'm trying strings, etc, but it always {}
). 因为我的模块不是我想的nodejs模块,所以无论如何
myModule
返回简单的{}
,但不是真正的值(我正在尝试字符串等,但总是{}
)。 How should I test this kind of code? 我应该如何测试这种代码?
Update : 更新 :
And what if i wouldn't use modules at all? 如果我根本不使用模块怎么办? Tested js file may be very simple:
经过测试的js文件可能非常简单:
var Config = {isDev: true};
Is it testable? 是否可以测试?
Thanks 谢谢
You could add code like this at the end of your module: 您可以在模块末尾添加如下代码:
if ( typeof module === 'object' && module.exports) {
module.exports = myModule;
}
A typical browser environment does not have module
defined in the global space, so this will export your module if you are running in Node. 典型的浏览器环境在全局空间中未定义
module
,因此如果您在Node中运行,它将导出您的模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.