kharandziuk
kharandziuk

Reputation: 12920

Proper way to share dependencies in Karma with RequireJS

I use Karma and jasmine for my unit tests. I have a main-test.js file to configure karma, and a main.js to configure my application.

main-test.js:

//
...
//
require.config({
  baseUrl: '/base',
  paths: {
    jquery: 'components/jquery/dist/jquery', // this is copypaste
    //another dependencies
  },
  //
  ...configuration
  //
});

main.js

require.config({
  paths: {
    jquery: 'components/jquery/dist/jquery', // this is copypaste
    //another dependencies
  },
  //
  ...configuration
  //
});

What is the proper way to share paths between those two configurations?

Upvotes: 1

Views: 430

Answers (1)

glepretre
glepretre

Reputation: 8167

We met the same problem with my team and ended up by requiring the main config into test-main.js:

// requiring global requireJS config
require(['/base/config/require.conf.js'], function() {
  'use strict';

  // first require.config overload: Karma specific
  require.config({
    baseUrl: '/base/src',

    paths: {
      'angularMocks': '../bower_components/angular-mocks/angular-mocks'
    },

    shim: {
      'angularMocks': {
        deps: ['angular']
      }
    }
  });

  require(['angularMocks'], function() {

    var specFiles = [];
    for (var file in window.__karma__.files) {
      if (window.__karma__.files.hasOwnProperty(file)) {
        if (/\/base\/src\/.*_test\.js$/.test(file)) {
          specFiles.push(file);
        }
      }
    }

    // second overload to include specFiles and start Karma
    require.config({
      deps: specFiles,
      callback: window.__karma__.start
    });
  });
});

Our starter app structure for projects using AngularJS + RequireJS is available here: angular-requirejs-ready.

I do not claim this is the proper way, only our way ;)

Upvotes: 2

Related Questions