title: KarmaJS, Jasmine, RequireJS, etc: How to Use Require for Testing Modules
body: <h1>Running Karma + Jasmine Tests with RequireJS -- Getting off the ground</h1>
  <h3>Help! . . . _ _ _ . . . SOS!</h3>
  <p>Currently, I have an exercise project up for getting comfortable with KarmaJS -- and Unit Testing, at large. The broad issue is that I really have no transparent view of what Karma is doing behind the scenes, and I can't seem to find adequate documentation in relevant areas. Without further delay...</p>
  <p>Here is my <strong>folder structure</strong>:</p>
  <pre><code>root
      |-/lib
          |-/[dependencies] (/angular, /angular-mocks, /bootstrap, /etc)  # from bower
      |-/src                                                              
          |-/[unreferenced directories] (/js, /css, /views)               # not referenced anywhere
          |-app.js                                                        # sets up angular.module('app', ...)
          |-globals.js                                                    # may be referenced in RequireJS main file; not used.
          |-index.html                                                    # loads bootstrap.css and RequireJS main file
          |-main.js                                                       # .config + require(['app', 'etc'])
          |-routeMap.js                                                   # sets up a single route
          |-test-file.js                                                  # *** simple define(function(){ return {...}; })
      |-/test
          |-/spec
              |-test-test-file.js                                         # *** require || define(['test-file'])
      |-.bowerrc                                                          # { &quot;directory&quot;: &quot;lib&quot; }
      |-bower.json                                                        # standard format
      |-karma.conf.js                                                     # *** HELP!
      |-test-main.js                                                      # *** Save Our Souls!!!
  </code></pre>
  <hr />
  <p><em><strong>karma.conf.js</strong></em></p>
  <pre><code>// Karma configuration
  // Generated on Wed Nov 19 2014 15:16:56 GMT-0700 (Mountain Standard Time)
  
  module.exports = function(config) {
    config.set({
  
      // base path that will be used to resolve all patterns (eg. files, exclude)
      basePath: '',
  
  
      // frameworks to use
      // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
      frameworks: ['jasmine', 'requirejs'],
  
  
      // list of files / patterns to load in the browser
      files: [
        //'test/spec/test-test-file.js',
        //'lib/**/*.js',
        //'src/**/*.js',
        //'test/spec/**/*.js',
        'test-main.js',
        {pattern: 'lib/**/*.js', included: false},
        {pattern: 'src/**/*.js', included: false},
        {pattern: 'test/spec/*.js', included: true}
      ],
  
  
      // list of files to exclude
      exclude: [
          'lib/**/!(angular|angular-mocks|angular-resource|angular-route|require|text).js',
          'lib/**/**/!(jquery|bootstrap).js',
          'src/app.js'
      ],
  
  
      // preprocess matching files before serving them to the browser
      // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
      preprocessors: {
      },
  
  
      // test results reporter to use
      // possible values: 'dots', 'progress'
      // available reporters: https://npmjs.org/browse/keyword/karma-reporter
      reporters: ['progress'],
  
  
      // web server port
      port: 9876,
  
  
      // enable / disable colors in the output (reporters and logs)
      colors: true,
  
  
      // level of logging
      // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
      logLevel: config.LOG_INFO,
  
  
      // enable / disable watching file and executing tests whenever any file changes
      autoWatch: true,
  
  
      // start these browsers
      // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
      browsers: ['Chrome'],
  
  
      // Continuous Integration mode
      // if true, Karma captures browsers, runs the tests and exits
      singleRun: false
    });
  };
  </code></pre>
  <p><em><strong>test-main.js</strong></em></p>
  <pre><code>var allTestFiles = [];
  var TEST_REGEXP = /(spec|test)\.js$/i;
  
  var pathToModule = function(path) {
      return path.replace(/^\/base\//, '').replace(/\.js$/, '');
  };
  
  Object.keys(window.__karma__.files).forEach(function(file) {
      if (TEST_REGEXP.test(file)) {
          // Normalize paths to RequireJS module names.
          allTestFiles.push(pathToModule(file));
      }
  });
  
  require.config({
      // Karma serves files under /base, which is the basePath from your config file
      baseUrl: '/base/src',
      
      paths: {
          
          angular: '../lib/angular/angular',
          ngRoute: '../lib/angular-route/angular-route',
          jquery: '../lib/jQuery/dist/jquery',
          bootstrap: '../lib/bootstrap/dist/js/bootstrap',
          models: 'models',
          controllers: 'controllers',
          globals: 'globals',
          routeMap: 'routeMap'
      },
      shim: {
          angular: {
              exports: 'angular'
          },
          ngRoute: {
              deps: ['angular']
          },
          jquery: {
              exports: '$'
          },
          bootstrap: {
              deps: ['jquery']
          }
      },
  
      // dynamically load all test files
      deps: allTestFiles,
  
      // we have to kickoff jasmine, as it is asynchronous
      callback: window.__karma__.start
  });
  </code></pre>
  <p><em><strong>test-test-file.js</strong></em></p>
  <pre><code>console.log('....................');
  
  define(function(){
      //console.log('testing test-file', testFile);
      
      describe('Testing testing', function(){
          it('should work', function(){
              expect(true).toEqual(true);
          });
      });
  
  });
  </code></pre>
  <p><em><strong>test-file.js</strong></em></p>
  <pre><code>define('testFile', [], function(){
      
      return function init(sandbox){
          var app, application = app = sandbox.app
            , globals = sandbox.globals;
          
          return {
              some: 'module'
          };
      };
      
  });
  </code></pre>
  <hr />
  <p><strong>Questions &amp; Descriptions</strong></p>
  <p>Key points I would love to hear answers for are</p>
  <ul>
  <li>what does { pattern: '...', <strong>include: true|false</strong> } do?</li>
  <li>best way to exclude all the extra stuff inside the bower directories.</li>
  <li>what files do I need to include in the test-main.js file?</li>
  <li>what files do I need to include in the karma.conf.js file?</li>
  <li>what does test-main.js actually do; what's it for?</li>
  </ul>
  <p>The times I receive errors &amp; issues is as soon as I wrap my spec in a <code>define(...)</code> call -- event when I give the module an ID -- <code>define('someId', function(){ ... })</code> -- <em>do I need to return something out of this module, as it is a <code>define</code> call?</em></p>
  <p>Other times, I receive the 'ol <em>ERROR: 'There is no timestamp for /base/src/app.js!'</em>. &quot;Timestamp, of course! How silly of me...&quot; -- what in the world does this mean?! Sometimes I get the infamous &quot;<em>Executed 0 of 0 ERROR</em>&quot; -- I could also use some clarity here, please. Really, I get plenty of <em>ERROR: '...no timestamp...'</em> errors -- and even <code>404</code>s when it <em>seems</em> I should be pulling that library in with the karma.conf.js <code>files</code> config...???</p>
  <p>It even seems that usually when I explicitly tell karma to exclude<code>src/app.js</code> I still get <code>404</code>s and errors.</p>
  <p><strong>tl;dr</strong></p>
  <p>Obviously, I'm a bit of a confused novice about Karma and *DD at large...</p>
  <p>I can run <code>test-test-file.js</code> fine when my karma.conf.js <code>files</code> array looks like <code>[ 'test-main.js', 'test/spec/test-test-file.js' ]</code> -- but, still, if I wrap my test in a RequireJS define call I get the &quot;<em>Mismatching anonymous define()</em>&quot; error mentioned above.</p>
  <p>It seems that when I add <em>{ pattern: '...', include: <strong>false</strong> }</em> then karma just doesn't add any of my files for the given pattern whatsoever (???).</p>
  <p>If someone can even simply direct me toward how to use RequireJS with Karma -- namely so that I can just wrap my tests in a <em>define/require</em> call and pull in the module I want to test... That would be greatly appreciated.</p>
  <p>As its somewhat difficult to keep these types of questions short and still provide adequate information, I hope I didn't make it too long.</p>
  <hr />
  <h3>EDIT</h3>
  <p>After reading the answer from glepretre and some fiddling on my own, I reconfigured my project as follows:</p>
  <ul>
  <li>Moved <code>test-main.js</code> to <code>test/test-main.js</code>,</li>
  <li>renamed <em>test-test-file.js</em> to <em>testFileSpec.js</em> -- moved it from <code>test/spec</code> to <code>test/</code>,</li>
  </ul>
  <p><em><strong>karma.conf.js:</strong></em></p>
  <pre><code>...
  // list of files / patterns to load in the browser
  files: [
      {pattern: 'lib/**/*.js', included: false},
      {pattern: 'src/**/*.js', included: false},
      {pattern: 'test/**/*Spec.js', included: false},
      
      'test/test-main.js'
    
  ],
  ....
  </code></pre>
  <p><strong>test/test-main.js:</strong></p>
  <pre><code>/* **************** HOW COME THE DEFAULT (Karma-generated) CONFIGURATION DOES ***NOT WORK???
  var allTestFiles = [];
  var TEST_REGEXP = /(spec|test)\.js$/i;
  
  var pathToModule = function(path) {
      return path.replace(/^\/base\//, '').replace(/\.js$/, '');
  };
  
  Object.keys(window.__karma__.files).forEach(function(file) {
      if (TEST_REGEXP.test(file)) {
          // Normalize paths to RequireJS module names.
          allTestFiles.push(pathToModule(file));
      }
  });
  */
  
  var tests = [];
  for (var file in window.__karma__.files) {
      if (/Spec\.js$/.test(file)) {
          tests.push(file);
      }
  }
  
  require.config({
      // Karma serves files under /base, which is the basePath from your config file
      baseUrl: '/base/src',
      
      paths: {},
      shim: {},
  
      // dynamically load all test files
      //deps: allTestFiles,
      //
      deps: tests,
  
      // we have to kickoff jasmine, as it is asynchronous
      callback: window.__karma__.start
  });
  </code></pre>
  <p><strong>I am now running Unit Tests successfully! <em>Special Thanks to glepretre &amp; all other contributors</em>.</strong></p>
  <hr />
  <p>Thanks for any insight at all :)</p>