Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Karma: Can't find variable: exports

I've written a node module which can be used for both the backend and client

(exports || window).Bar= (function () {
    return function () { .... }
})();

Now my karma tests use PhantomJs and complain about the not existing exports variable

gulp.task('test', function () {
    var karma = require('karma').server;

    karma.start({
        autoWatch: false,
        browsers: [
            'PhantomJS'
        ],
        coverageReporter: {
            type: 'lcovonly'
        },
        frameworks: [
            'jasmine'
        ],
        files: [
            'bar.js',
            'tests/bar.spec.js'
        ],
        junitReporter: {
            outputFile: 'target/junit.xml'
        },
        preprocessors: {
            'app/js/!(lib)/**/*.js': 'coverage'
        },
        reporters: [
            'progress',
            'junit',
            'coverage'
        ],
        singleRun: true
    });
});

The error I get is

PhantomJS 1.9.7 (Mac OS X) ERROR
   ReferenceError: Can't find variable: exports

Is there a way to ignore the exports variable in karam/phantomsJs ?

like image 476
Jeanluca Scaljeri Avatar asked Oct 04 '14 11:10

Jeanluca Scaljeri


1 Answers

A common pattern is usually to check whether the exports variable is defined:

(function(){
  ...
  var Bar;
  if (typeof exports !== 'undefined') {
    Bar = exports;
  } else {
    Bar = window.Bar = {};
  }
})();

This pattern is used in Backbone as example - well, it's technically bit more complicated in the source code because it does support also AMD, but the idea it's this.

You can also push down the check passing it as first argument of the wrapping function:

(function(exports){

  // your code goes here

  exports.Bar = function(){
      ...
  };

})(typeof exports === 'undefined'? this['mymodule']={}: exports);

Have a look at this blog post for more info.

like image 179
MarcoL Avatar answered Sep 29 '22 15:09

MarcoL