我正在尝试通过路由器的解决方案测试接收对象的控制器:
app.js:
... .when('/confirm',{ templateUrl: 'views/confirm.html',controller: 'ConfirmCtrl',resolve: { order: function(Order) { return Order.current; } } }) ...
ConfirmCtrl.js:
angular.module('angularGeolocationApp').controller('ConfirmCtrl',function($scope,order,...) { $scope.order = order ... });
我的测试看起来像这样:
'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(); }); ... });
然而,第一次期望失败:
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.
我的假设是,当我对隔离控制器进行单元测试时,路由器没有更改来运行resolve函数并分配正确的值.
有没有办法模拟订单依赖?
我知道我可以摆脱解决方案并在控制器本身中注入Order并将$scope.order实例化为Order.current,但我想保留解决方法.
只需将自己的顺序放入ctrl的构造函数中,就像这样.
describe('Controller: 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(); }); ... });
问候