Last Updated: February 25, 2016
·
5.519K
· eskimoblood

Mock/stub your requirejs dependecies

Using requirejs makes it easy to mock or stub all your dependencies. You have to create a new context for your test where you can overide the path to your dependencies and define mocks for them:

function createContext(stubs) {

  /**
   * create a new map which will override the path to a given dependencies
   * so if we have a module in m1, requiresjs will look now unter   
   * stub_m1
   **/
  var map = {};

  _.each(stubs, function (value, key) {
    var stubname = 'stub_' + key;

    map[key] = stubname;


  });

  /**
   * create a new context with the new dependency paths
   **/
  var context =  require.config({
    context: Math.floor(Math.random() * 1000000),
    map: {
      "*": map
    }
  });

  /**
   * create new definitions that will return our passed stubs or mocks
   **/
  _.each(stubs, function (value, key) {
    var stubname = 'stub_' + key;

    define(stubname, function () {
      return value;
    });

  });

  return context;

}

In your test you pass a JSON with your stubs and get the context in which you can run your test:

define('m1', ['app'], function (app) {
  app.start('test');
});

(function () {
  //create stubs
  var stubs = {
    app: {start: jasmine.createSpy()}
  };
  //get context
  var context = createContext(stubs);
  //start test in the context
  context(['m1'], function (m1) {

    describe("m1", function () {

      it("start the app with the string 'test'", function () {
        expect(stubs.app.start).toHaveBeenCalledWith('test');
      });

    });
  });
})();

3 Responses
Add your response

I can't seem to get this to work… if I ever use the context variable for getting dependencies, none of the jasmine tests in that function seem to register. Have you ever seen that issue?

The mocks are correctly created and my modules are loaded… I can log right above the describe() function call but they simply don't register.

over 1 year ago ·

I'm getting "Cannot read property 'suites' of undefined" occasionally =/

over 1 year ago ·

ok ok, I found the problem… I'm executing the jasmine environment before the code in the context runs… how do you make sure it's done in the right order?

over 1 year ago ·