AngularJS:Mock对象通过路由器的解析注入控制器

jvi*_*tti 7 unit-testing angularjs karma-runner

我正在尝试测试通过路由器的解析接收对象的控制器:

app.js:

...
.when('/confirm', {
  templateUrl: 'views/confirm.html',
  controller: 'ConfirmCtrl',
  resolve: {
    order: function(Order) {
      return Order.current;
    }
  }
})
...
Run Code Online (Sandbox Code Playgroud)

ConfirmCtrl.js:

angular.module('angularGeolocationApp').controller('ConfirmCtrl',
function($scope, order, ...) {

  $scope.order = order

  ...

});
Run Code Online (Sandbox Code Playgroud)

我的测试看起来像这样:

'use strict';

describe('Controller: ConfirmCtrl', function () {

  // load the controller's module
  beforeEach(module('angularGeolocationApp'));

  var ConfirmCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    ConfirmCtrl = $controller('ConfirmCtrl', {
      $scope: scope
    });
  }));

  it('should get an order object', function () {
    expect(_.isObject(scope.order)).toBeTruthy();
  });

  ...
});
Run Code Online (Sandbox Code Playgroud)

然而,第一次期望失败:

PhantomJS 1.9.2 (Mac OS X) Controller: ConfirmCtrl should get an order object FAILED
    TypeError: Attempted to assign to readonly property.
        at workFn (/Users/jviotti/Projects/Temporal/angular/angular-geolocation/app/bower_components/angular-mocks/angular-mocks.js:2107)
    Expected false to be truthy.
Run Code Online (Sandbox Code Playgroud)

我的假设是,当我对隔离控制器进行单元测试时,路由器没有更改来运行resolve函数并分配正确的值.

有没有办法模仿这种order依赖?

我知道我可以摆脱解决方案并注入Order并实例化$scope.orderOrder.current控制器本身,但我想保持这种resolve方法.

kfi*_*fis 13

只需将您自己的顺序放入ctrl的构造函数中,就像这样.

describe('Controller: ConfirmCtrl', function () {

  // load the controller's module
  beforeEach(module('angularGeolocationApp'));

  var ConfirmCtrl,
      scope,
      order


  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    order = {};
    scope = $rootScope.$new();
    ConfirmCtrl = $controller('ConfirmCtrl', {
      $scope: scope,
      order: order
    });
  }));

  it('should get an order object', function () {
    expect(_.isObject(scope.order)).toBeTruthy();
  });

  ...
});
Run Code Online (Sandbox Code Playgroud)

问候