Angularjs 无法调用预期的函数
我确信我正在做的是一个很容易解决的问题,但我似乎无法发现它。测试的功能如下:Angularjs 无法调用预期的函数,angularjs,karma-runner,Angularjs,Karma Runner,我确信我正在做的是一个很容易解决的问题,但我似乎无法发现它。测试的功能如下: function signIn(credentials) { return $http({ url: 'auth/authenticate', skipAuthorization: true, method: 'POST', data: credentials }).then(function (result) { saveCredentials(result.data)
function signIn(credentials) {
return $http({
url: 'auth/authenticate',
skipAuthorization: true,
method: 'POST',
data: credentials
}).then(function (result) {
saveCredentials(result.data);
});
};
它在$http的承诺返回后调用saveCredentials函数。我正在这样测试它:
(function() {
describe('Unit Testing: Auth-service Factory',function() {
var AuthService, httpBackend, deferred;
beforeEach(module('flowlens'));
// Mock values for jwt and store
beforeEach(function() {
module(function($provide) {
$provide.value('jwtHelper',{
decodeToken: function() {
return {
contact: 'Joe Bloggs'
}
}
});
$provide.value('store',{
set: function() {}
});
});
});
// Get the service
beforeEach(function() {
inject(function(_AuthService_, _$httpBackend_) {
AuthService = _AuthService_;
httpBackend = _$httpBackend_;
});
});
describe('should load the service',function() {
it('service should be loaded',function() {
expect(AuthService).not.toBeUndefined();
});
});
describe('signIn',function() {
it('should return data when calling signIn', function() {
spyOn(AuthService,'saveCredentials');
httpBackend.expectPOST('auth/authenticate').respond({msg: 'Success'});
AuthService.signIn();
httpBackend.flush();
expect(AuthService.saveCredentials).toHaveBeenCalled();
});
});
});
}());
这条线上方的期望值在以下方面失败:
Expected spy saveCredentials to have been called
为什么不叫这个?我在函数中添加了一条日志消息,我可以看到代码中正在调用它-这是$scope.digest问题吗?请注意,如果我添加以下内容:
it('should return data when calling signIn', function() {
spyOn(AuthService,'saveCredentials');
httpBackend.expectPOST('auth/authenticate').respond({msg: 'Success'});
AuthService.signIn().then(function(result) {
AuthService.saveCredentials(result);
// Assuming that I have mocked it before the call
});
httpBackend.flush();
expect(AuthService.saveCredentials).toHaveBeenCalled();
});
它会过去的。但这是一个假测试,因为我可以继续,将实际调用更改为一个完全不同的方法,它仍然会通过
我做错了什么?您可以在
中尝试您的期望,然后(…)
函数:
it('should return data when calling signIn', function() {
spyOn(AuthService,'saveCredentials');
httpBackend.expectPOST('auth/authenticate').respond({msg: 'Success'});
AuthService.signIn().then(function(result) {
expect(AuthService.saveCredentials).toHaveBeenCalled();
});
httpBackend.flush();
});
我认为在单元测试中不需要
then
。你只要打电话给signIn
和spyOnsaveCredentials
,然后(在flush
之后)谢谢你的反馈-不幸的是,这也没用。你有我可以看的JSFIDLE或PLUNK吗?我不抱歉-但我相信我已经找到了问题所在。测试似乎失败,因为AuthService对象实际上是空的。所以它本质上是检查一个无法调用的函数