Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Jasmine UI router inject resolve value into test

In my Angular app, UI router resolves a promise into the controller. When trying to test this controller, Karma is complaining about an unknown provider. How do I inject a fake object into the test to represent this resolve object.

My app's code looks something like:

angular.module('myapp')
.config(function($stateProvider, $urlRouterProvider) {
    $stateProvider
    .state('tab.name', {
        ...
        resolve: {
            allTemplates: function(Templates) {
                return Templates.all().then(function(templates) {
                    return templates;
                });
            }
        }
    })
})
.controller('QueriesCtrl', function(allTemplates, UserQuery) {
    var vm = this;
    vm.queries = allTemplates;
    vm.goToUrl = function(index, data) {
        var processedUrl = UserQuery.process(data, vm.queryTyped[index]);
        UserQuery.goToUrl(processedUrl);
    };
});

When trying to run tests I get the error

Unknown provider: allTemplatesProvider <- allTemplates <- QueriesCtrl

I've tried creating a spy and injecting it, but this does not work. Here's my test at the moment:

describe('Unit: queriesCtrl', function() {
    var controller,
        scope,
        UserQuery;

    beforeEach(function() {
        module('myapp');
        inject(function($injector) {
            UserQuery = $injector.get('UserQuery');
            allTemplates = jasmine.createSpyObj('allTemplates', [{a:1}, {a:2}, {b:3}]);
        });
    });

    describe('goToUrl', function() {
        beforeEach(inject(function ($rootScope, $controller) {
            scope = $rootScope.$new();
            controller = $controller('QueriesCtrl as ctrl', {
                '$scope': scope
            });
        }));
        it('should call UserQuery.process()', function() {
            spyOn(UserQuery, 'process');
            scope.ctrl.goToUrl();
            expect(UserQuery.process).toHaveBeenCalled();
        });
    });
});
like image 217
Fisu Avatar asked Feb 17 '15 08:02

Fisu


1 Answers

Since there is no route involved in unit test you would have to inject the allTemplates as a normal object with $controller function. Can you try:

controller = $controller('QueriesCtrl as ctrl', {
                '$scope': scope,
                 'allTemplates':allTemplates 
            });

Else you can use the $provide API to create a dummy service.

 module(function ($provide) {
    $provide.value("allTemplates", {[{a:1}, {a:2}, {b:3}]});

Do it first thing in your beforEach block.

like image 180
Chandermani Avatar answered Sep 20 '22 18:09

Chandermani