單元測試應該只關心它的測試組件。您不需要測試$ location的實際功能,而是需要時調用該方法。你也不關心API服務做什麼,只是當令牌是虛假的,控制器調用位置方法。
我想:
模擬服務API
。
間諜$location.path
方法。
設置API.token
至true
。
檢查$location.path
尚未被調用。
設置API.token
到false
檢查$location.path
被稱爲與參數 「/」。
像這樣:
describe('Controller: MainCtrl', function() {
// Define this test's local variables
var scope,
$location,
MainCtrl;
// Load the controller's module
beforeEach(angular.mock.module('app'));
/* jshint camelcase:false */
// Initialize the controller and scope
beforeEach(angular.mock.inject(function($controller, $rootScope, _$location_) {
scope = $rootScope.$new();
$location = _$location_;
spyOn($location, 'path');
MainCtrl = $controller('MainCtrl', {
$scope: scope,
API: {token: false},
$location: $location
});
}));
it('should exist', function() {
expect(MainCtrl).toBeTruthy();
});
describe('when created', function() {
it('should call $location accordingly', function() {
expect($location.path).toHaveBeenCalledWith('/');
});
});
});
任何代碼示例將不勝感激。 – Iladarsda
你走了。編輯我的答案。 – Wawy
重要的是要提到'spy'需要在創建'ctrl'之前定義。 – Iladarsda