Why do I see “define not defined” when running a Mocha test with RequireJS?

前端 未结 5 1742
暗喜
暗喜 2020-12-23 20:22

I am trying to understand how to develop stand-alone Javascript code. I want to write Javscript code with tests and modules, running from the command line. So I have insta

5条回答
  •  星月不相逢
    2020-12-23 20:48

    The reason your test isn't running is because src/utils.js is not a valid Node.js library.

    According to the RequireJS documentation, in order to co-exist with Node.js and the CommonJS require standard, you need to add a bit of boilerplate to the top of your src/utils.js file so RequireJS's define function is loaded.

    However, since RequireJS was designed to be able to require "classic" web browser-oriented source code, I tend to use the following pattern with my Node.js libraries that I also want running in the browser:

    if(typeof require != 'undefined') {
        // Require server-side-specific modules
    }
    
    // Insert code here
    
    if(typeof module != 'undefined') {
        module.exports = whateverImExporting;
    }
    

    This has the advantage of not requiring an extra library for other Node.js users and generally works well with RequireJS on the client.

    Once you get your code running in Node.js, you can start testing. I personally still prefer expresso over mocha, even though its the successor test framework.

提交回复
热议问题