单元测试中的范围变量

时间:2016-07-13 18:58:46

标签: angularjs unit-testing karma-jasmine

我使用karma / jasmine进行单元测试,并且在测试我的控制器时遇到错误。 控制器代码:

angular.module('app.controllers', [])
    .controller('myctrl1',[function($scope){
        $scope.test = "this worked";
    }])

单元测试代码:

describe('Controllers', function(){ //describe your object type
    beforeEach(module('app.controllers')); //load module<br />
    describe('Running Test for :',function(){ //describe your app name<br />
        var myctrl;
        beforeEach(inject(function($controller){ //instantiate controller using $controller service
            myctrl = $controller('myctrl1');
        }));
        it('Test scope var', function(){  //write tests
            expect($scope.test).toBe('this worked'); //pass
        });
    });
});

我收到以下错误:

TypeError: Cannot set property 'test' of undefined
ReferenceError: $scope is not defined

1 个答案:

答案 0 :(得分:3)

测试修改为:

angular.module('app.controllers', ['ngMockE2E'])

.controller('myCtrl1', function($scope) {
  $scope.test = "this worked";
});

describe('Main Controller test suite', function() {

  describe('myCtrl1', function() {
    var $scope;

    beforeEach(module('app.controllers'));

    beforeEach(inject(function($rootScope, $controller) {
      $scope = $rootScope.$new();
      $controller('myCtrl1', {
        $scope: $scope
      });
    }));

    it('Test scope var', function() {
      expect($scope.test).toBe('this worked'); //pass
    });
  });
});
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-mocks.js"></script>
</head>

<body>
  <h1>Angular controller test with Jasmine</h1>
</body>

</html>

参考: https://docs.angularjs.org/guide/unit-testing#testing-a-controller