我确定我所做的事情很容易解决,但我似乎无法发现它。测试中的功能是:
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();
});
它会通过。但这是一个假测试,因为我可以继续将实际调用更改为完全不同的方法,它仍然会通过。
我做错了什么?
答案 0 :(得分:1)
您可以在then(...)
函数中尝试您的期望:
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();
});