Mark Bell Mark Bell - 1 year ago 49
Javascript Question

How do I test 'normal' (non-Node specific) JavaScript functions with Mocha?

This seems like it should be extremely simple; however, after two hours of reading and trial-and-error without success, I'm admitting defeat and asking you guys!

I'm trying to use Mocha with Should.js to test some JavaScript functions, but I'm running into scoping issues. I've simplified it down to the most basic of test cases, but I cannot get it working.

I have a file named

, which just contains the following:

function testFunction() {
return 1;

And my
(located in the same folder) contents:


describe('tests', function(){
describe('testFunction', function(){
it('should return 1', function(){

This test fails with a
ReferenceError: testFunction is not defined

I can see why, because most of the examples I've found either attach objects and functions to the Node
object or export them using
—but using either of these approaches means my function code would throw errors in a standard browser situation, where those objects don't exist.

So how can I access standalone functions which are declared in a separate script file from my tests, without using Node-specific syntax?

Answer Source

That doesn't do anything since you're not exporting anything. What you're expecting is that testFunction is globally available, essentially the same as

global.testFunction = function() {
    return 1;

You just can't bypass the export/globals mechanism. It's the way node has been designed. There is no implicit global shared context (like window on a browser). Every "global" variable in a module is trapped in it's context.

You should use module.exports. If you intend to share that file with a browser environments, there are ways to make it compatible. For a quick hack just do window.module = {}; jQuery.extend(window, module.exports) in the browser, or if (typeof exports !== 'undefined'){ exports.testFunction = testFunction } for node.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download