Skip to content

Instantly share code, notes, and snippets.

@alicial
Last active June 10, 2019 14:26
Show Gist options
  • Select an option

  • Save alicial/7681791 to your computer and use it in GitHub Desktop.

Select an option

Save alicial/7681791 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
});
@iammerrick

Copy link
Copy Markdown

One neat way to do it is like so...

beforeEach(module({
  UserService: {
    get: function() {
      return { id: 8888, name: 'test user' };
    }
  }
});

beforeEach(inject(function(MyController) {
  // Receives UserService
}));

@alicial

alicial commented Nov 28, 2013

Copy link
Copy Markdown
Author

@iammerrick I used to use regular objects to mock services, but found using $q.when() invaluable for mocking methods that return promises, just edited to include an example.

@jerridan

Copy link
Copy Markdown

Thanks @alicial for sharing this! I've been trying to get something very similar to work for a while now, your example really helped.

@vivisera

Copy link
Copy Markdown

I'm getting such error when running the test:

Error: [$injector:unpr] Unknown provider: Provider <- <- UserService.

Any hint?

@karipireddy

Copy link
Copy Markdown

@alicial thanks, very informative gist, it saved lot of time while figuring to mock my service.
do you have any suggestions for securing the angularjs app, is passportjs good to use on angularjs ?

@vivisera have you included the mocked-servces.js file in karma conf file ? i guess that would be the solution.
i understand this is old question, it will clarify if you can add how you resolved.

@toboqus

toboqus commented Oct 23, 2014

Copy link
Copy Markdown

Just wanted to say thanks for the gist, it's saved me alot of time mocking up my services.

@leshow

leshow commented Dec 11, 2014

Copy link
Copy Markdown

great gist, thanks.

@seanislegend

Copy link
Copy Markdown

Thanks from me too!

@lcustodio

Copy link
Copy Markdown

Great gist @alicial! I've question related to this. How would I mock the service in a directive instead? Is the same approach reusable?

@cyrilchaponeverysens

Copy link
Copy Markdown

Hey =)

Greaat gist. Thanks. I've been looking for this for long.

I experienced weird issues when mocking like

  var getListDeferred;
  beforeEach(module(function($provide) {
    $provide.service('thingApi', function($q) {
      this.getList = jasmine.createSpy('getList').and.callFake(function() {
        var deferred = $q.defer();
        getListDeferred = deferred;
        return deferred.promise;
      });
    });
  }));

So I'm gonna try your solution.

@Ankitg44

Ankitg44 commented Feb 6, 2016

Copy link
Copy Markdown

Hey Alicial, thanks for the solution.

@RicardoAlmeida25

Copy link
Copy Markdown

Thanks for this ;)

@rei-kurzweil

Copy link
Copy Markdown

More helpful than SO. Cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment