Skip to content

Instantly share code, notes, and snippets.

@gregjsmith
Created February 14, 2014 07:15
Show Gist options
  • Save gregjsmith/8996993 to your computer and use it in GitHub Desktop.
Save gregjsmith/8996993 to your computer and use it in GitHub Desktop.
Test setup for Angular / QUnit / Sinon
var serviceLocator = angular.injector(['ng', 'nameOfAngularApp']); // used to get dependencies like controllers / filters etc
var scope = {}; // a clean scope to test
var $controllers = serviceLocator.get('$controller'); //get injector that can retrieve controllers
var $filters = serviceLocator.get("$filter"); // get filter injector
var someService; // define a global used in all tests
QUnit.module('the module name', { // define the module - qualify with QUnit namespace to avoid conflict with Angular
setup: function () {
scope = serviceLocator.get('$rootScope').$new(); // get a clean scope
$controllers('theControllerBeingTested', { $scope: scope }) // get the controller to test
someService = serviceLocator.get('someService'); // get a service defined in your application
}
});
test('some test name', function(){
var result = scope.doThings(); // call things on the scope
ok(result);
var aFilter = $filters("theFilterName"); // get filter by name
var newResult = aFilter(result); // apply a filter
ok(newResult);
});
test("with a stubbed service", function(){
var stub = sinon.stub(someService, 'getThings' function(){ //stub the "getThings" method on someService
return [1, 2, 3, 4, 5, 6] //return known result set from this method
});
$controllers('controllerBeingTested', {$scope: scope, someService: someService}) //setup the controller with scope and stub service
var result = scope.doTHings();
ok(result.somethingHappened)
stub.restore(); //reset the mocking library to ensure subsequent tests are clean
});
test("with a spy", function(){
var spy = sinon.spy(someService, 'getThings'); //spy on the getTHings method
$controllers('controllerBeingTested', {$scope: scope, someService: someService}); //setup controller with dependencies
scope.doTHings();
ok(spy.calledOnce); //verify things on the spied-on dependency
spy.restore(); //reset mocking
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment