Я пытаюсь понять, как тестировать js файлы. Послушайте, у меня есть файл emotify.js с функцией:
function emotify(string) {
return string + '' + ' :)';
}
и затем я создал другой файл - index.js с содержимым ниже:
var emotify = require('./emotify.js');
console.log(emotify('just testing'));
но консоль натолкнет меня на ошибку
TypeError: emotify is not a function
Что случилось?
Когда вам требуется модуль, результатом будет то, что модуль экспортировал. В этом случае вам нужно будет экспортировать вашу функцию:
Код эмоции.js:
module.exports = function(string) {
return string + '' + ' :)';
}
emotify.js:
module.exports = function emotify(string) { // Named function, good for call stack at debugging. You are pro, right ?
return string + '' + ' :)';
}
test.js:
const emotify = require('./emotify.js'); // const instead of var, cause you are pro :)
console.log(emotify('just testing'));
mylib.js:
function emotify(string) {
return string + '' + ' :)';
}
function anotherFunc(string) {
return string + '' + ' :)';
}
module.exports = {
emotify,
anotherFunc,
};
test.js:
const mylib = require('./mylib.js');
console.log(mylib.emotify('just testing'));
console.log(mylib.anotherFunc('just testing'));
================
Полезные ссылки: