[英]testing js files using nodejs
I try to understand how to test js files. 我尝试了解如何测试js文件。 Look, I have a file emotify.js with function: 看,我有一个带有功能的emotify.js文件:
function emotify(string) {
return string + '' + ' :)';
}
and then I created another file - index.js with the content below: 然后我创建了另一个文件-index.js,内容如下:
var emotify = require('./emotify.js');
console.log(emotify('just testing'));
but console push me an error 但是控制台向我推一个错误
TypeError: emotify is not a function
What is wrong ? 怎么了 ?
When you require a module the result is what the module have exported. 当您需要模块时,结果就是模块导出的结果。 In this case you will need to export your function: 在这种情况下,您将需要导出函数:
emotify.js code: emotify.js代码:
module.exports = function(string) {
return string + '' + ' :)';
}
emotify.js: emotify.js:
module.exports = function emotify(string) { // Named function, good for call stack at debugging. You are pro, right ?
return string + '' + ' :)';
}
test.js: test.js:
const emotify = require('./emotify.js'); // const instead of var, cause you are pro :)
console.log(emotify('just testing'));
mylib.js: mylib.js:
function emotify(string) {
return string + '' + ' :)';
}
function anotherFunc(string) {
return string + '' + ' :)';
}
module.exports = {
emotify,
anotherFunc,
};
test.js: test.js:
const mylib = require('./mylib.js');
console.log(mylib.emotify('just testing'));
console.log(mylib.anotherFunc('just testing'));
================ ================
Useful links: 有用的链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.