我很难搞清楚为什么在我的测试中没有调用http.post方法,这是由消息说“无需刷新”以及将console.log语句添加到成功和错误承诺方法。
使用应用程序时,api代码可以正常工作。这是我的第一个角度控制器测试,所以我可能会遗漏一些简单的东西。
我一直在使用David Mosher的示例作为模板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)
答案 0 :(得分:0)
正如评论中提到的,我使用的是角度1.1.5(对于新的ng-animate)。为了让我的测试通过,我需要安装角度模拟1.1.5。
bower install angular-mocks-unstable
或更新bower.js(或components.js)文件并运行:
bower install
并更新我的karma.conf.js文件
files = [
JASMINE,
JASMINE_ADAPTER,
'app/components/angular-unstable/angular.js',
'app/components/angular-mocks-unstable/angular-mocks.js', // need unstable here
'.tmp/scripts/*.js',
'.tmp/scripts/**/*.js',
'.tmp/spec/**/*.js'
];