Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to set up amdefine in tests so that I don't have to define it in all my module files?

I have a set of objects that are used browser side but tested server side with mocha. I'm using require.js for AMD loading. The Require.js site suggests using amdefine on server-side to get the defined modules to work in node.js with this bit of code:

if (typeof define !== 'function') {
    var define = require('amdefine')(module)
}

OK. But I have to put that into every module that I want to use in Node. In my case that means I have to strip it out of any code that I'm using client side (most of it).

I'm wondering if there's any way to put that chunk of code in my test instead so that I don't have to put it in my client side code. It seems silly to have code in my files that will only be needed for the tests -- makes more sense to put it in the test code. However, when I do that I get an error:

Error: amdefine with no module ID cannot be called more than once per file.
    at runFactory (/home/vmplanet/dev/alpha/web/node_modules/amdefine/amdefine.js:159:23)
    at define (/home/vmplanet/dev/alpha/web/node_modules/amdefine/amdefine.js:275:13)
    at Object.<anonymous> (/home/vmplanet/dev/alpha/web/assets/src/coffee/delta/dataLayer.coffee:4:3)
    at Object.<anonymous> (/home/vmplanet/dev/alpha/web/assets/src/coffee/delta/dataLayer.coffee:158:4)
    at Module._compile (module.js:456:26)
    at Object.loadFile (/usr/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:179:19)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)

It's an odd error, since the amdefine code is only in one place -- the top of the test file. Is there a way to put this amdefine code in my test and only my test and still get the tests to run server side -- without having to strip out the amdefine code for client side?

like image 478
jcollum Avatar asked Nov 03 '22 22:11

jcollum


1 Answers

If you use amd-loader, you can do this:

require("amd-loader");
var datatypes = require("../build/dist/lib/salve/datatypes");
var name_resolver = require("../build/dist/lib/salve/name_resolver");

That's it. You just require amd-loader first and then you can load AMD-style modules at will. (In the example above the two modules loaded after amd-loader are AMD-style modules.) And the AMD-style modules can load other AMD-style modules.

The snippet above is actual code from one of my test suites which tests a library designed AMD-style so that it can be loaded with RequireJS but is tested in Node.js.

like image 160
Louis Avatar answered Nov 11 '22 04:11

Louis