【问题标题】:Injecting routerProvider for AngularJS test using Jasmine使用 Jasmine 为 AngularJS 测试注入 routerProvider
【发布时间】:2015-03-05 13:20:47
【问题描述】:

我正在使用 Jasmine 测试 AngularJS 控制器,我正在努力寻找将 $routeProvider 注入模块的方法。

这是我的控制器:

var app = angular.module('testApp', []);

app.config(['$routeProvider',
  function ($routeProvider) {
      $routeProvider.
          when('/smth', {
              templateUrl: 'smth.html',
              controller: 'testController'
          });
  }]);

app.controller('testController', ['$scope', function ($scope) {
    $scope.data = 'GG';
}]);

这是我的测试:

describe('Test Suite', function () {
    var myScope, ctrl;

    beforeEach(module('testApp'));

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

    it('data is GG', function () {
        expect(myScope.data).toEqual('GG');
    });
});

当我尝试运行它时,我收到以下错误:

Error: [$injector:modulerr] Failed to instantiate module testApp due to:
Error: [$injector:unpr] Unknown provider: $routeProvider

但如果我再次尝试运行 - 我会得到:

TypeError: 'undefined' is not an object (evaluating 'myScope.data')

如果再次运行测试,错误会不断交替。我正在使用 Visual Studio 2013 和 Resharper 8 来运行 Jasmine 测试。

【问题讨论】:

    标签: angularjs testing jasmine provider inject


    【解决方案1】:

    将 angular-route bower 组件添加到您的项目中,然后像这样将 ngRoute 注入到您的模块中

    var app = angular.module('testApp', ['ngRoute']);
    app.config(['$routeProvider', function ($routeProvider) {
      $routeProvider.
          when('/smth', {
              templateUrl: 'smth.html',
              controller: 'testController'
          });
    }]);
    
    app.controller('testController', ['$scope', function ($scope) {
        $scope.data = 'GG';
    }]);
    

    【讨论】:

      【解决方案2】:

      首先确保您已包含 angular-route.min.js。 该模块已从 angularJs 库中分离出来,因此您必须单独包含它

      然后确保您已将模块的依赖项添加到 ngRoute 例如angular.module('testApp', ['ngRoute']);

      然后在测试中确保您注入 $route 以便它在您的测试中也可用

      【讨论】:

        猜你喜欢
        • 2014-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-14
        • 1970-01-01
        • 1970-01-01
        • 2014-09-20
        相关资源
        最近更新 更多