0
我很難弄清楚爲什麼http.post方法沒有在我的測試中被調用,這是由消息說〜「什麼都不沖洗」,以及添加console.log語句同時指向成功和錯誤承諾方法。無法通過角度控制器測試
使用應用程序時,api代碼可以正常工作。這是我的第一個角度控制器測試,所以我可能會錯過簡單的東西。
我一直用大衛·毛思迪的例子作爲模板https://github.com/davemo/lineman-angular-template/blob/master/spec/controllers/login_controller_spec.coffee
# controller
"use strict"
angular.module("woddlyApp").controller "SignupCtrl", ($scope, $http, $location) ->
$scope.user = {}
$scope.save = (user, role) ->
user.role = role
$http.post('/users', user)
.success (data, status, headers, config) ->
$location.path '/dashboard'
.error (data, status, headers, config) ->
# tests
'use strict'
describe 'Controller: SignupCtrl', ->
# load the controller's module
beforeEach -> module('woddlyApp')
# Initialize the controller and a mock scope
beforeEach inject ($controller, $rootScope, @$location, @$httpBackend) ->
@scope = $rootScope.$new()
@redirect = spyOn($location, 'path')
$controller 'SignupCtrl', { $scope: @scope, $location: $location }
afterEach ->
@$httpBackend.verifyNoOutstandingRequest()
@$httpBackend.verifyNoOutstandingExpectation()
describe 'Successful signup', ->
beforeEach ->
@$httpBackend.expectPOST('/users', @scope.user).respond(200)
@scope.save(@scope.user, 'member')
@$httpBackend.flush()
it 'redirects the user to the dashboard page', ->
expect(@redirect).toHaveBeenCalledWith '/dashboard'
錯誤
Chrome 28.0 (Linux) Controller: SignupCtrl Successful signup redirects the user to the dashboard page FAILED
Error: No pending request to flush !
at Error (<anonymous>)
at Function.$httpBackend.flush (/home/chris/projects/personal/woddly/client/app/components/angular-mocks/angular-mocks.js:1195:34)
at null.<anonymous> (/home/chris/projects/personal/woddly/client/.tmp/spec/controllers/signup.js:25:34)
Expected spy path to have been called with [ '/dashboard' ] but it was never called.
Error: Expected spy path to have been called with [ '/dashboard' ] but it was never called.
at null.<anonymous> (/home/chris/projects/personal/woddly/client/.tmp/spec/controllers/signup.js:30:38)
Error: Unsatisfied requests: POST /users
at Error (<anonymous>)
at Function.$httpBackend.verifyNoOutstandingExpectation (/home/chris/projects/personal/woddly/client/app/components/angular-mocks/angular-mocks.js:1228:13)
at null.<anonymous> (/home/chris/projects/personal/woddly/client/.tmp/spec/controllers/signup.js:19:32)
你試過設置斷點來驗證保存方法實際上被調用?檢查控制檯是否有錯誤消息? – ivarni
我沒有添加斷點,但是我在$ http.post調用之前和之後添加了一些console.log語句,並且在測試期間都被觸發了 – chris
您是否已編譯javascript?我幾年沒碰過CoffeeScript ......如果我正確地閱讀了代碼,我就像你一樣困惑,但如果你有一個簡單的方法將它編譯爲JS並將其放在pastebin或github的要點或某物上我可能會有更多的運氣。 – ivarni