简体   繁体   中英

passing $scope to $scope in jasmine to test angularjs controller

Below is a valid jasmine test case, but I'm confused with this line

var controller = $controller('CalculatorController', { $scope: $scope });

^ Why we need to declare the second argument, and pass in $scope : $scope. Isn't that should be default? Because in angularjs your controller for sure will have scope.

describe('calculator', function () {

    beforeEach(angular.mock.module('calculatorApp'));

    var $controller;

    beforeEach(angular.mock.inject(function(_$controller_){
      $controller = _$controller_;
    }));

    describe('sum', function () {
        it('1 + 1 should equal 2', function () {
            var $scope = {};
            var controller = $controller('CalculatorController', { $scope: $scope });
            $scope.x = 1;
            $scope.y = 2;
            $scope.sum();
            expect($scope.z).toBe(3);
        }); 
    });

});

Controller Dependencies

Controller's don't just have a $scope , when you declare your controller as follows:

myApp.controller("appController", function ($scope){
    // controller code here
});

what you're actually doing is declaring a dependency on $scope . That is, that the controller must be given the $scope before it can carry out it's work. Another syntax for the above is:

myApp.controller("appController", ["$scope", function ($scope){
    // controller code here
}]);

That syntax means to inject the angular service with a name of "$scope" into the variable $scope , and so the variable $scope then becomes your controller's scope.

Testing Controllers with Dependencies

When testing a controller, the tests are based on the controllers scope. Using the $controller service you create your controller and pass in all of the dependencies.

The { $scope: $scope } part of the code you highlight is where you specify the controller dependencies. What you are saying there is "use the $scope that I'm creating here in my test as the controller's $scope ". You could call the second $scope anything, it just happens to be called the same thing locally in your test as in the controller. This is also fine:

var myScope = {};
var controller = $controller('CalculatorController', { $scope: myScope });

Then you run actions against the controller and the idea is that those actions change the values held on the scope. Then you can run expectations against the state held on the scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM