我有一个AngularJS 1.5应用程序,我使用UI-Router。我遇到的问题是单元测试控制器内的状态变化。
我的控制器中有以下逻辑
CostingsController = ($scope, $http, $state, flash) ->
if $state.current.name == "costing_new"
if $scope.current_division
$http.get('/costings/new').then ((response) ->
$scope.costing = response.data
)
else
flash("alert", "Please select a division", 2000)
$state.go "divisions"
我正在尝试测试当没有选择分区时状态会变为分区。此代码在实践中有效,但在测试中无效。这是我的Jasmine测试
describe "when division is not selected", ->
beforeEach(inject ( ($controller, $rootScope, $location, $state, $httpBackend) ->
@state = $state
@redirect = spyOn(@state, 'go')
@state.transitionTo('costing_new')
ctrl = $controller('CostingsController', {
$scope: @scope,
$location: $location,
$state: @state
})
))
it "redirects to division", ->
expect(@state.go).toHaveBeenCalledWith('divisions')
我得到的错误是;
Chrome 63.0.3239 (Linux 0.0.0) CostingsController Controller: costings_controller new when division is not selected redirects to division FAILED
Expected spy go to have been called with [ 'divisions' ] but it was never called.
at Object.<anonymous> (/home/map7/code/pais/spec/javascripts/unit/costing_controller_spec.js.js:47:40)
Chrome 63.0.3239 (Linux 0.0.0): Executed 1 of 394 (1 FAILED) (skipped 393) ERROR (0.403 secs / 0.197 secs)
更新:使用angular.copy
describe "when division is not selected", ->
beforeEach(inject ( ($controller, $rootScope, $location, $state, $httpBackend) ->
@state = angular.copy({current: {name: 'costing_new'}}, $state)
@redirect = spyOn(@state, 'go')
ctrl = $controller('CostingsController', {
$scope: @scope,
$location: $location,
$state: @state
})
))
it "redirects to division", ->
expect(@state.go).toHaveBeenCalledWith('divisions')
如果我使用上面的angular.copy,我会收到以下错误;
TypeError: Cannot set property current of #<StateService> which has only a getter
答案 0 :(得分:0)
采取行动帮助我嘲笑这样的状态
describe "when division is not selected", ->
beforeEach(inject ( ($controller, $state) ->
@state = {
current: {name: "costing_new"},
go: jasmine.createSpy("go")
}
ctrl = $controller('CostingsController', {
$scope: @scope,
$state: @state
})
))
fit "redirects to division", ->
expect(@state.go).toHaveBeenCalledWith('divisions')