Angular Jasmine UI router inject resolve value into test
Asked Answered
I

1

12

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();
        });
    });
});
Implausible answered 17/2, 2015 at 8:37 Comment(0)
F
12

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.

Fruitful answered 17/2, 2015 at 9:21 Comment(1)
@ Chandermani, I am new to mocha-Chai , could please help out with similar issue posted at #28606556Undaunted

© 2022 - 2024 — McMap. All rights reserved.