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

后端 未结 3 934
清酒与你
清酒与你 2020-12-23 13:06

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! <

相关标签:
3条回答
  • 2020-12-23 13:08

    If you want to make any module available through require you should use

    module.exports
    

    as you know ;)

    there is a solution if you want to use a module in Node and in browser by doing this

    function testFunction() { /* code */ }
    
    if (typeof exports !== 'undefined') {
       exports.testFunction = testFunction
    }
    

    by doing this you will be able to use the file in browser and in node environment

    0 讨论(0)
  • 2020-12-23 13:17
    require('./functions.js')
    

    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.

    0 讨论(0)
  • 2020-12-23 13:25

    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);
            })
        })
    })
    
    0 讨论(0)
提交回复
热议问题