Angular Jasmine UI router inject resolve value int

2019-02-12 07:23发布

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();
        });
    });
});

1条回答
Fickle 薄情
2楼-- · 2019-02-12 07:49

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.

查看更多
登录 后发表回答