Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access "global" mocha.js functions when using require.js

I am including Mocha.js with the excellent use shim for a Require.js-based site.

How do I access the define() and it() BDD functions declared by Mocha when using Require.js?

Here is a basic code example:

test.js:

var mocha    = require('use!mocha')
  , testFile = require('testFile.js')

mocha.setup('bdd');
mocha.run();

testFile.js:

define(function(require) {
  // describe() and it() are not available
  describe('Book', function() {
    it('should have pages', function() {

    });
  });
});

I get the error Uncaught ReferenceError: describe is not defined when running in the browser.

I have tried window.describe and tried moving the require('testFile.js') to after the mocha.setup('bdd'). I know I am missing something. Probably passing the context to mocha somehow.

like image 931
baalexander Avatar asked Feb 20 '12 22:02

baalexander


2 Answers

The problem is that the global functions such as describe and it are set up by mocha.setup(). You can use shim config's init property to call mocha.setup() before mocha is exported.

requirejs.config({
  shim: {
    'mocha': {
      init: function () {
        this.mocha.setup('bdd');
        return this.mocha;
      }
    }
  }
});

require(['mocha', 'test/some_test'], function (mocha) {
  mocha.run();
});

Test files need to require mocha.

define(['mocha'], function (mocha) {    
  describe('Something', function () {
    // ...
  });
});

Shim config's init property was introduced in RequireJS 2.1. You might be able to use exports property instead of init with RequireJS 2.0.

like image 108
Shuhei Kagawa Avatar answered Nov 08 '22 14:11

Shuhei Kagawa


I found the solution in geddski's amd-testing examples project.

Instead of including the test file(s) at the top along with mocha like so:

define(['use!mocha', 'testFile'],
function(Mocha, TestFile) {
  mocha.setup('bdd');
  mocha.run();
});

The test file(s) should be included as another require call and mocha.run() embedded in the callback:

define(['use!mocha'],
function(Mocha) {
  mocha.setup('bdd');

  // Include the test files here and call mocha.run() after.
  require(['testFile'],
  function(TestFile) {
    mocha.run();
  });
});
like image 35
baalexander Avatar answered Nov 08 '22 16:11

baalexander