Search code examples
javascriptnode.jsmocha.jsamd

Importing AMD module in to Mocha test


I am using Mocha to test code exported as AMD module. Running mocha test gives me following error.

ReferenceError: define is not defined
at Object.<anonymous> (/home/malintha/projects/...../xxx.js:1:63)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)

The source which is tested as floows

define(['lodash', 'log', './yyy'], function(_, log, YYY) {

var xxxy = function() {

};

..............
});

And the mocha test

var expect    = require("chai").expect;
var sourceGenVisitor = require("../../xxx")

describe("", function() {
 describe("", function() {
  it("Checks generated source", function() {
     ...................
  });
  });
 });

How can I fix this issue ?


Solution

  • You can use amd-loader. I used it for years in a project of mine that was structured as a collection of AMD modules. Install with:

    `npm install amd-loader`
    

    It then needs to be loaded before any AMD module. In general:

    require("amd-loader");
    

    For Mocha you can use the argument --require amd-loader. You can put it in your test/mocha.opts file if you don't want to have to remember typing it over and over.