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

Thanks to the other answers here, I’ve got things working.

One thing which wasn’t mentioned though—perhaps because it’s common knowledge among Noders—was that you need to assign the result of the require call to a variable, so that you can refer to it when calling your exported functions from within the test suite.

Here’s my complete code, for future reference:

functions.js:

function testFunction () {
    return 1;
}

// If we're running under Node
if (typeof exports !== 'undefined') {
    exports.testFunction = testFunction;
}

tests.js:

var myCode = require('./functions')

describe('tests', function(){
    describe('testFunction', function(){
        it('should return 1', function(){
            // Call the exported function from the module
            myCode.testFunction().should.equal(1);
        })
    })
})

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)