I\'m trying to figure out on how to test internal (i.e. not exported) functions in nodejs (preferably with mocha or jasmine). And i have no idea!
Let say I have a mo
The trick is to set the NODE_ENV environment variable to something like test and then conditionally export it.
Assuming you've not globally installed mocha, you could have a Makefile in the root of your app directory that contains the following:
REPORTER = dot
test:
@NODE_ENV=test ./node_modules/.bin/mocha \
--recursive --reporter $(REPORTER) --ui bbd
.PHONY: test
This make file sets up the NODE_ENV before running mocha. You can then run your mocha tests with make test at the command line.
Now, you can conditionally export your function that isn't usually exported only when your mocha tests are running:
function exported(i) {
return notExported(i) + 1;
}
function notExported(i) {
return i*2;
}
if (process.env.NODE_ENV === "test") {
exports.notExported = notExported;
}
exports.exported = exported;
The other answer suggested using a vm module to evaluate the file, but this doesn't work and throws an error stating that exports is not defined.