2013-12-13 68 views
7

我試圖測試接收對象槽路由器的決心控制器:AngularJS:模擬對象注入到控制器低谷路由器的決心

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. 

我的假設是因爲我的單元測試分離器,路由器沒有改變運行的決心功能和分配正確的值。

有沒有辦法模擬order依賴關係?

我知道我可以擺脫的決心東西,注入Order和實例$scope.order在控制器本身Order.current,但我想保持resolve方法。

回答

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(); 
    }); 

    ... 
}); 

問候

+0

如果一些測試後,我想改變'order'的價值是什麼。我怎麼做? –