AngularJS + Jasmine Noob:如何在规范中访问$ scope?

时间:2014-08-05 15:50:04

标签: angularjs

这是我第一次使用Jasmine进行测试。我在访问规范中的$ scope变量时遇到了问题。我的测试失败了:

mysite ProductsDetailCtrl sets hey
  Expected undefined to be 1.
    Error: Expected undefined to be 1.

规格:

//= require helpers/load-angular-mysite-module
//= require products/controllers/products_detail_controller

describe('mysite', function() {
  var $rootScope, $scope, $controller;
  beforeEach(function() {
    module('mysite');
  });

  describe('ProductsDetailCtrl', function() {
    beforeEach(inject(function(_$rootScope_, _$controller_) {
      $rootScope = _$rootScope_;    // don't really
      $scope = $rootScope.$new();   // understand what's
      $controller = _$controller_;  // going on in this function

      controller = $controller('ProductsDetailCtrl', {
        '$rootScope': $rootScope,
        '$scope': $scope
      });
    }));

    it('sets hey', function() {
      expect($rootScope.hey).toBe(1);
    });
  });

});

控制器:

app.controller('ProductsDetailCtrl', ['$scope', '$resource', function($scope, $resource) {
  $scope.hey = 1;
 ....

有人可以向我解释我将如何访问范围吗?

1 个答案:

答案 0 :(得分:2)

您只需检查hey中不属于$scope的<{1}}内的财产$rootScope

describe('mysite', function() {
  var scope, ProductsDetailCtrl;

  beforeEach(function() {
    module('mysite');
  });

  describe('ProductsDetailCtrl', function() {
    beforeEach(inject(function($controller, $rootScope) {
      // Create a mock scope for your controller.
      scope = $rootScope.$new();
      // Initialize the controller with the mocked scope.
      ProductsDetailCtrl = $controller('ProductsDetailCtrl', {
        $scope: scope
      });
    }));

    it('sets hey', function() {
      expect(scope.hey).toBe(1);
    });
  });

});