andree
andree

Reputation: 3224

angular auto mocking controller/service dependencies

In Angular unit testing, it takes a lot of unnecessary code to mock/stub all depencencies manually, especially when all I need are some generic mocks. Also, when dependency list changes for service/controller, tests break because of missing dependencies.

In C#, there is a way to reconfigure DI container to automatically mock all dependencies, when Resolve() is called. I want something like that in Angular.

I want to go from this:

beforeEach(inject(function ($controller, $rootScope, agsRest) {
        scope = $rootScope.$new();      

        sut = $controller('SearchController', {
            $scope: scope
            , map: {}
            , agsRest: agsRest
            , config: {}
            , core: {}
            , myPopup: {}
            , popupFormatter: {}
        });
    }));

To something like this:

beforeEach(inject(function ($controller, $rootScope, agsRest) {
        scope = $rootScope.$new();      

        sut = autoMock("SearchController"); // instance of SearchController is returned, which has all dependencies mocked with sinon/jasmine/whatever
    }));

Is there some kind of library / code to do this?

Upvotes: 3

Views: 639

Answers (2)

kris_IV
kris_IV

Reputation: 2444

You should look for ng-improved-testing. It's create auto-mock for all injected services (you need only add "Mock" to services name when you inject them).

Link to GitHub: https://github.com/evangalen/ng-improved-testing

Upvotes: 0

mostruash
mostruash

Reputation: 4189

I've needed something similar and came up with this small utility library: tentacle.js. I'm up to suggestions and to pull requests for bettering the API.

Upvotes: 1

Related Questions