我正在尝试对node.js模块进行单元测试,我想知道如何正确导出varibles和对象?所以我可以在我的单元测试中访问它们并对它们进行处理。
源代码:
var someObject = {};
var Array = [189, 347, 497, 632, 750, 900, 995, 1137],
someNumber = 142,
sizeOfArray = Allowance.length;
someObject = {
method1 : function (info) {
//something...
return {
someOtherMethod1: someObject.method1(info) && someObject.method2(info)
someOtherMethod2: someObject.method3(info)
};
},
method2 : function (info) {
//something...
return something2;
}
method3 : function (info) {
//something...
return something3;
}
};
module.exports = someObject;
通过这样做:
module.exports = someObject;
我能够在mocha中访问单元测试文件中的someObject,但是如何访问其他变量,如Array,sizeOfArray,someNumber?
我已尝试添加此内容:
module.exports = {
someObject : someObject,
Array : Array,
someNumber : someNumber,
sizeOfArray : sizeOfArray
};
但是我的单元测试文件无法读取它
修改
这是我的单元测试
var assert = require("assert")
var expect = require("expect.js")
var chai = require("chai")
var sourceCode = require('../src/sourceCode')
describe("Something..", function() {
var Info = {
//some data...
};
describe("Properties", function() {
it("has someObject defined", function() {
expect(someObject).not.to.be.undefined;
});
it("has Array defined", function() {
expect(Array).not.to.be.undefined;
});
it("has someNumber defined", function() {
expect(someNumber).not.to.be.undefined;
});
it("has sizeOfArray defined", function() {
expect(sizeOfArray).not.to.be.undefined;
})
})
describe("Methods", function() {
it("should have method1 defined", function() {
expect(sourceCode.someObject.method1(Info)).not.to.be.undefined;
});
it("should have method2 defined", function() {
expect(sourceCode.someObject.method2(Info)).not.to.be.undefined;
});
})
};
@Augusto
这就是我在测试Method1
时所说的it("should return positive when conditions are met", function() {
var result = sourceCode.someObject.method1(Info);
expect(result).not.to.be.undefined;
expect(result.eligible).not.to.be.undefined;
expect(sourceCode.result.someOtherMethod2).not.to.be.undefined;
expect(sourceCode.result.someOtherMethod1).to.equal(true);
});
答案 0 :(得分:1)
我认为问题出在你的单元测试中。您没有访问对象中的属性
var sourceCode = require('../src/sourceCode');
//CODE CODE CODE
expect(Array).not.to.be.undefined;
您尝试访问 Array 变量而不是 sourceCode.Array 属性。由于您没有定义 Array 变量,因此您收到了未定义的错误消息。正确的代码将是:
expect(sourceCode.Array).not.to.be.undefined;
所以..在你的单元测试中试试这个:
var assert = require("assert")
var expect = require("expect.js")
var chai = require("chai")
var sourceCode = require('../src/sourceCode')
describe("Something..", function() {
var Info = {
//some data...
};
describe("Properties", function() {
it("has someObject defined", function() {
expect(sourceCode.someObject).not.to.be.undefined;
});
it("has Array defined", function() {
expect(sourceCode.Array).not.to.be.undefined;
});
it("has someNumber defined", function() {
expect(sourceCode.someNumber).not.to.be.undefined;
});
it("has sizeOfArray defined", function() {
expect(sourceCode.sizeOfArray).not.to.be.undefined;
})
})
};