mercredi 7 octobre 2015

Jasmine Angular unit testing: controller with an external variable

I'm trying to write a unit test for a controller which uses a $scope.action variable defined outside the controller.

controller( "MyController", [
    "$scope", "$window", "httpInterceptor",
    function($scope, Service1, Service2, $window, httpInterceptor) {
            $scope.init = function() { ... });
            $scope.action.cb.write = function() { ... };
            $scope.action.cb.read = function() { ... };
        }]
);

My unit test is as follows.

describe("The controller", function () {
    var $controller, $scope, httpInterceptor, window, httpBackend;

beforeEach(function() {
    inject(function(_httpInterceptor_, _$controller_, _$rootScope_, $httpBackend, $http) {
        $scope = _$rootScope_.$new();
        httpInterceptor = _httpInterceptor_;
        httpBackend = $httpBackend;
        window = {setTimeout: function() {}};
        $controller = _$controller_("MyController", {
            httpInterceptor: _httpInterceptor_, $scope: $scope, $window: window, $http: $http
        });})});
afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});

describe("The init() method", function () {
    it("Init method", function () {
        $scope.$parent.action = {}
        $scope.init();
    });});});

I get an error TypeError: Cannot read property "cb" from undefined. I'm confused why I get this error as I'm trying to test only the init function. I initially tried mocking $scope.$parent.action = {} as $scope.action = {} to no avail.

Thanks.

Aucun commentaire:

Enregistrer un commentaire