Skip to content

Instantly share code, notes, and snippets.

@refractalize
Created December 11, 2012 00:27
Show Gist options
  • Save refractalize/4254642 to your computer and use it in GitHub Desktop.
Save refractalize/4254642 to your computer and use it in GitHub Desktop.
How to bootstrap AngularJS with mock dependencies, in unit tests...

Unittesting AngularJS directives

At some point, you'll want to test your angular JS directives in the DOM. This means adding a DOM element, invoking angular on it and then running your browser test. But you'd like to inject some different dependencies, perhaps a stub, or a mock, so you can get a reliable test result, or even spy on its behaviour.

As you can see below, this is quite straightforward, although it may not seem to be at first. What you need to do is call angular.bootstrap passing in your DOM element, followed by a list of modules. You'll probably pass in your main module, but you'll have the opportunity to pass in other modules that override some dependencies with mocks or stubs. These take the form of a function that accepts a $provide parameter, that can be used to override various factorys and other injectables.

Finally, you'll have to wait for the next tick to let angular re-render the DOM. Then finally you can run your test.

// your app
myapp = angular.module('myapp', []);
myapp.directive('userView', function () {...});
myapp.factory('userApi', function () {...});
describe("create view modal", function() {
beforeEach(function(done) {
// create the element with the directive under test
$("#test").append("<div user-view></div>");
// a module function, taking $provide as dependency
var apis = function($provide) {
// override the factory with the mock/stub
$provide.factory("userApi", function() {...});
};
// bootstrap the DOM with angular and your app, passing in the mock module function
angular.bootstrap($("#test")[0], ["myapp", apis]);
// give angular a chance to refresh the dom, ready for your tests
setTimeout(done, 0);
});
it('can ...', function () {
// get on and poke around
$('#test button').click();
...
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment