我正在Jasmine写我的第一个Angular测试,我似乎无法在模拟服务中得到消化的承诺。 这是我的控制器(正在测试)及其使用的资源:
'use strict';
angular.module('myApp.login', [
'ngCookies',
'ngResource'
])
/*Controllers*/
.controller('login', ['$scope', '$rootScope', '$cookies', 'LoginService', function ($scope, $rootScope, $cookies, LoginService) {
$scope.user = {};
$scope.user.username = "";
$scope.user.password = "";
var loginError = function () {
console.log("failure logging in")
};
var loginSuccess = function (result) {
$cookies.put('authToken', result.token);
$rootScope.loggedIn = true;
};
$scope.login = function () {
var credentials = {username: $scope.user.username, password: $scope.user.password};
var tokenPromise = LoginService.authenticate(credentials);
console.log(tokenPromise);
tokenPromise.$promise.then(loginSuccess, loginError);
}
}])
/*Resources*/
.factory('LoginService', ['$resource', 'apiUrl', function ($resource, apiUrl) {
return $resource(
apiUrl + 'auth/token/',
{},
{
authenticate: {
method: "POST"
}
}
)
}]);
以下是测试的当前版本。
describe('myApp.login', function () {
var createController, scope, deferred, LoginService;
var successToken = {'token': 'tokenGoesHere'}
beforeEach(inject(function($rootScope, $controller, $injector, $q, $timeout) {
var cookies = $injector.get('$cookies');
scope = $rootScope.$new();
LoginService = { authenticate: function(user) {
deferred = $q.defer();
$timeout(function(){
deferred.resolve(successToken);
$rootScope.$apply();
$rootScope.$digest();
}, 1000);
$timeout.flush();
return deferred.promise;
}};
return $controller('login', {
'$scope': scope,
'$cookies': cookies,
'LoginService': LoginService
});
};
}));
it('Should set cookie with returned JWT', function() {
var controller = new createController();
scope.user.username = 'username';
scope.user.password = 'password';
scope.login();
});
});
我尝试了$timeout
,setTimeout
,spyOn
和其他几个,但我尝试的任何内容都不会在控制器期望的状态下返回承诺,而我最终会得到以下stacktrace:
PhantomJS 1.9.8 (Linux 0.0.0) myApp.login Should set cookie with returned JWT FAILED
TypeError: 'undefined' is not an object (evaluating 'tokenPromise.$promise.then')
at /home/anton/git/persist-ng/app/login/login.js:53
at /home/anton/git/persist-ng/app/login/login_test.js:42
PhantomJS 1.9.8 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.041 secs / 0.007 secs)
任何帮助都会受到赞赏,即使问题实际上存在于代码本身,而不是测试中。