Search code examples
javascriptunit-testingrequirejsmocha.jsamd

Configuring Require js to load AMD modules in javascript


I am new with writing test cases for testing my javascript files using gulp, mocha, chai.

My file directory

Project
|-- _src
|   `-- scripts
|       `-- ui
|           |-- ChangePos.js
|           |-- PosRenderer
|           `-- utils
|               |-- Element
|               `-- Config
`-- test
    `-- index.js

utils/ChangePos.js

 define(['Config',
            'Element',
            'PosRenderer'

] {
      function() {
      //mycode
      }
    });

It has dependency on Config and Element files.

test/index.js

var requirejs = require("requirejs");
var chai = require('chai');
var expect = chai.expect;

requirejs.config({
    baseUrl: './../_src/scripts/ui',
    paths: {
        utils: 'utils'
    },

    nodeRequire: require,
    map: {
        '*': {
            'NIT.Cookie': 'utils/Element'
        }
    }
});

    describe('almeObjectConfig', function() {
        var ele, conf, obj;
        before(function (done) {
            requirejs(['utils/Config', 'utils/Element'],
                function (config, element) {
                    console.log('Configuration: ' + config);
                    console.log('Element: ' + element);
                ele = element;
                conf = config;
                done();
            });
        });

I am trying to load ChangePos which has dependency on Element and Config by specifying path 'utils'.

utils: 'utils'

I can load Element explicitly by specifying baseURL as baseUrl:'./../_src/scripts/ui/utils' but here it is checking only inside ui folder and giving an undefined object.

It works if I put all files in ui folder as it is considering the base URL and looking only inside the base folder.

I am not sure what am I missing here. Thanks for the help inadvance.


Solution

  • Looking at your configuration I see nothing that would allow ChangePos to load utils/Element as Element and utils/Config as Config. In particular, the paths configuration 'utils': 'utils' does not do this, and does nothing at all with the specific configuration you have. To get the code you have to work, you'd have to have paths be:

    paths: {
        'Config': 'utils/Config',
        'Element': 'utils/Element'
    }