因果报应茉莉花和角度控制器使用'控制器为'语法(this而不是$scope)

Karma jasmine and angular controller using 'Controller as' syntax (this instead of $scope)

本文关键字:控制器 this scope 语法 茉莉花 因果报应      更新时间:2023-09-26

我正试图设置因果报应来进行一些单元测试,但我无法使其在一个基本示例上工作:

这是控制器文件:

angular.module('balrogApp.requests', [
  /* Dependancies */
])
  // Routes configuration
  .config(['$routeProvider', function($routeProvider) {
    /* $routeProvider configuration */
  }])
  .controller('requestsController', function(Requests, Users, Projects, RequestsComments, CostEstimations,
                                             Regions, growl, $route, $rootScope, $scope, $location) {
    this.test = 'test42';
/* ... */
});

这是测试文件:

describe('requestsController', function() {
  beforeEach(module('balrogApp.requests'));
  var ctrl;
  beforeEach(inject(function($controller) {
    ctrl = $controller('requestsController');
  }));
  it('should have test = "test42"', function(){
    expect(ctrl.test).toBe("test42");
  });
});

但是这个错误被抛出:

Chrome 43.0.2357(Windows 7 0.0.0)请求控制器应该进行测试="test42"失败错误:[$injector:unp]未知提供程序:$scopeProvider<-$作用域<-请求控制器http://errors.angularjs.org/1.4.7/$injector/unp?p0=%24范围提供者%20%3C-%20%24范围%20%3C-%20请求控制器网址:C:''Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/aangular.js:68:12网址:C:''Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/aangular.js:4289:19在Object.getService[as-get](C:''Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:4437:39)位于C:''Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/aangular.js:4294:45在getService(C:''/Users/aazor102115/Desktop/Def/Balrog/bower_components/angular/aangular.js:4437:39)调用时(C:''Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/aangular.js:4469:13)在Object.instantiate(C:''Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/aangular.js:4486:27)网址:C:''Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/aangular.js:9151:28在C:''Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular mocks/aangular mock.js:1882:12在对象处。(C:''Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:6:12)错误:申报位置在window.inject.aangular.mock.inject(C:''Users/aazor102115/Desktop/Dev/Barrog/bower_components/angular mocks/aangular mock.js:2409:25)套房。(C:''Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:5:14)位于C:''Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:1:1TypeError:无法读取未定义的属性"test"在对象处。(C:''Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:10:16)Chrome 43.0.2357(Windows 7 0.0.0):执行第1个(共1个失败)错误(0.108秒/0.087秒)

$scope(您的控制器所依赖的)是一个所谓的"本地",即它特定于控制器的实例,不存在于依赖注入容器中。您必须自己提供,例如:

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

既然你正在创建一个新的作用域,那么最好在测试后销毁它:

var scope;
beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    ctrl = $controller('requestsController', { $scope: scope });
}));
afterEach(function() {
    scope.$destroy();
});