yazz
yazz

Reputation: 301

Unknown Provider error using Karma with Angular

I have a module

export default angular.module('pfui.user', [])
    .controller('ModifyUserController', ModifyUserController)

that has a controller

export default class ModifyUserController{ 
    userid:string;
    ...
}

I'm trying to create a unit test that can test some methods in the controller that calls services to do some operation. This is my Karma script -

describe('ModifyUserControllerTester', function () {
    var $controller;
    beforeEach(angular.mock.module('ui.router'));
    beforeEach(angular.mock.module('pfui.user'));
    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
    }));

    describe('Test', function () {
        it('test accessing controller', function () {
            let $scope = {};
                var controller = $controller('ModifyUserController', {
                $scope: $scope
             });
            expect($scope['userid']).toBe(undefined);
        });
    });
});

When I run the test, I get an error

Error: [$injector:unpr] Unknown provider: UsersProvider <- Users <- ModifyUserController

Initially I was getting an error that $stateProvider was missing. So I added

beforeEach(angular.mock.module('ui.router'));

and that error went away.

This is my first attempt in writing a Karma test. I'm not sure what I am missing. Why is Karma looking for a Provider when I don't have one in the module? Any help is greatly appreciated.

Upvotes: 0

Views: 40

Answers (1)

the_makeshift_dev
the_makeshift_dev

Reputation: 196

Your question doesn't show any dependency injections to the ModifyUserController but going by the error you have posted it looks like you haven't provided the 'Users' Service to the controller.

describe('ModifyUserControllerTester', function () {
    var $controller;
    var mockUsers;
    beforeEach(angular.mock.module('ui.router'));
    beforeEach(angular.mock.module('pfui.user'));
    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
    }));

    describe('Test', function () {
        it('test accessing controller', function () {
        //----define your mock dependency here---//
        let mockUsers = jasmine.createSpyObj('mockUsers', ['user_method1', 
            'user_method2',...]);
            let $scope = {};
                var controller = $controller('ModifyUserController', {
                $scope: $scope,
                Users: mockUsers
            });
            expect($scope['userid']).toBe(undefined);
        });
    });
});

PS. Since its best practice for unit tests to be conducted in isolation, you should also consider providing a mock state provider vs importing the actual ui.router module

Upvotes: 1

Related Questions