Skip to content

Instantly share code, notes, and snippets.

@siddharth-pandey
Forked from alicial/mock-service-example.js
Created November 25, 2016 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siddharth-pandey/2e7dd18c9a54fce277a42d474e8a3809 to your computer and use it in GitHub Desktop.
Save siddharth-pandey/2e7dd18c9a54fce277a42d474e8a3809 to your computer and use it in GitHub Desktop.
AngularJS: Setting up a mocked service to use in controller unit tests.
// Mocked Service
angular.module('mock.users', []).
factory('UserService', function($q) {
var userService = {};
userService.get = function() {
return {
id: 8888,
name: "test user"
}
};
// example stub method that returns a promise, e.g. if original method returned $http.get(...)
userService.fetch = function() {
var mockUser = {
id: 8888,
name: "test user"
};
return $q.when(mockUser);
};
// other stubbed methods
return userService;
});
// Controller Unit Tests
describe('My Controller', function() {
var ctrl, scope;
beforeEach(module('module.containing.controller'));
// include previous module containing mocked service which will override actual service, because it's declared later
beforeEach(module('mock.users'));
beforeEach(inject(function($controller, $rootScope, _UserService_) { // inject mocked service
scope = $rootScope.$new();
ctrl = $controller('MyController', {
$scope: scope,
UserService: _UserService_
});
}));
// unit tests go here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment