2

I try to understand how to test js files. Look, I have a file emotify.js with function:

function emotify(string) {
 return string + '' + ' :)'; 
}

and then I created another file - index.js with the content below:

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 ?

1

2 Answers 2

3

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:

module.exports = function(string) {
 return string + '' + ' :)'; 
}
Sign up to request clarification or add additional context in comments.

Comments

1

Variant 1

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'));

Variant 2

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'));

================

Useful links:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.