Skip to content

Using Require.js with karma mocha webworker

Nicolas Oliver edited this page Jan 12, 2017 · 1 revision

karma.conf.js

mochaWebWorker: {
  // Import require.js lib using  `self.importScripts` in worker instance
  evaluate: {
    beforeMochaImport: 'self.importScripts(\'path/to/require.js\')'
  },
  // Set test-main.js as start point
  pattern : [
    'path/to/test-main.js'
  ],
}

test-main.js

/**
 * Wrap mocha.run function for delayed call
 */
let mochaRunFunction = mocha.run;
let mochaRunCallback = null;

mocha.run = function (cb) {
  console.log('Delayed mocha.run(cb) call');
  originalRunCallback = cb;
};

require.config({
  // Karma serves files under /base, which is the basePath from your config file
  baseUrl: '/base',
  // Add some specific Require.js configuration for your project..
  // Execute test after load
  callback: () => {
    require([
      // AMD module with source code 
      'path/to/file.js',
      // AMD module with test code
      'path/to/test.js'
    ], (file, test) => {
      // Execute test with mocha
      mochaRunFunction(mochaRunCallback);
    });
  }
Clone this wiki locally