Angularjs injected controller empty when testing with Jasmine

江枫思渺然 提交于 2019-12-22 06:32:25

问题


I am currently working with Angular and using Karma and Jasmine to make the testing. The filters, for example are injected to the main module and can be tested without any problem, but when I try to test the controllers I get an empty object after the injection.

Here is the code of my main module:

(function () {

    'use strict';

    var dependencies = [];

    angular.module('myApp', dependencies)

}());

The controller that I am to test:

(function () {
    'use strict';

    angular.module('myApp')

        .controller('NavCtrl', ['$scope',
            function ($scope) {

                $scope.currentUser = null;

            }]);
}());

And finally the test suite:

describe ("controller", function() {

    beforeEach(module("myApp"));

    var $scope, $rootScope, controllerLoader;

    beforeEach(inject(function($injector) {
        $rootScope = $injector.get('$rootScope');
        $scope = $rootScope.$new();

        var $controller = $injector.get('$controller');

        controllerLoader = function() {
            return $controller('NavCtrl', {
                '$scope': $scope
            });
        };
    }));

    it ("testing injection", function() {

        var controller = controllerLoader();
        expect(controller).toNotEqual({});

    })

});

But the result of the test is FAIL, and after debugging I see that the injected controller is empty. I have already tried to give a false name for the controller and the test just crashes, what means that the controller is detected but for any reason I am not getting its properties.


回答1:


I was having a similar issue. The difference is that in my application I am using RequireJS, so some parts are a little different, but I guess the overall might help you.

I modified it to match your names:

define(['app/app.module', 'angular', 'angular-mocks'], function () {

  describe('Controller Unit test', function () {

    var $controller;

    beforeEach(module('myApp'));

    beforeEach(inject(function (_$controller_) {
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $controller = _$controller_;
    }));

    describe('Get the controller', function () {
        it('should contain controller', function () {
            var $scope = {};
            var controller = $controller('NavCtrl', {$scope: $scope});

            console.log(controller);
            expect(controller).toBeDefined();
        });
    });
  });
});

It is very important to load both angular and angular-mocks. However I think the main issue is that your controllerLoader function is in beforeEach section. The injection has to be made in the describe section of the test itself.



来源:https://stackoverflow.com/questions/22632748/angularjs-injected-controller-empty-when-testing-with-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!