[英]Unit testing an inner function?
I have a function that has inner functions, for my unit test, I only want to test the functionality of the inner function, but when I export the function and call the inner function, npm tests returns an error. 我有一个具有内部函数的函数,对于我的单元测试,我只想测试内部函数的功能,但是当我导出函数并调用内部函数时, npm测试会返回错误。
In my main.js
: 在我的main.js
:
mainFunction = () => {
functionToBeTested = () => {
// some code
}
}
module.exports = {mainFunction: mainFunction}
In my test.js
在我的test.js
const chai = require("chai");
const assert = require("chai").assert;
const mainFunction = require("./main");
describe ("test", () => {
it("returns results", () => {
let result = mainfunction.functionToBeTested(args);
//equal code
});
})
But when I run npm test, it says: 但是当我运行npm测试时,它说:
mainfunction.functionToBeTested is not a function. mainfunction.functionToBeTested不是函数。
What am I doing wrong? 我究竟做错了什么?
If you want to chain your functions you can try something like that. 如果你想链接你的功能,你可以试试这样的东西。
main.js main.js
const mainFunction = () => {
const functionToBeTested = () => {
return "I got it";
}
return { functionToBeTested };
}
module.exports = { mainFunction };
test.js test.js
const chai = require("chai");
const assert = require("chai").assert;
const mainFunction = require("./main");
const mf = mainFunction();
describe ("test", () => {
it("returns results", () => {
let result = mf.functionToBeTested(args);
//equal code
});
});
Actually, you can't call a function declare inside another function that way. 实际上,你不能以这种方式调用另一个函数内部的函数声明。 A solution would be to declare functionToBeTested
outside mainFunction
, then call it : 一个解决方案是在mainFunction
外面声明functionToBeTested
,然后调用它:
main.js main.js
const functionToBeTested = () => {
// some code
};
const mainFunction = () => {
functionToBeTested();
};
module.exports = { mainFunction, functionToBeTested }
test.js test.js
const chai = require("chai");
const assert = require("chai").assert;
const { mainFunction, functionToBeTested } = require("./main");
describe ("test", () => {
it("tests mainFunction", () => {
let main = mainfunction(args);
...
});
it("tests functionToBeTested"), () => {
let tested = functionToBeTested(args);
...
});
})
It is because only mainFunction() is exported and not the functionToBeTested(), outside this module JS doesn't knows about the existence of the functionToBeTested(). 这是因为只导出mainFunction()而不是functionToBeTested(),在这个模块之外JS不知道functionToBeTested()的存在。
I will recommend you to move functionToBeTested separated and export that as well or have a helper method for calling it. 我建议你移动functionToBeTested并将其导出或者有一个帮助方法来调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.