我想变得更彻底,所以请多多包涵,这里会有很多事情。我们有一个远程日志记录服务功能,可以在需要时向我们发送一些客户端信息。像这样:
callHome: function(message){
var deferred, promise;
try{
if (someService.getRemoteLoggingEnabled())
{
//collect all the info into remoteLog
promise = $http.post("Logging", remoteLog);
wipeLog();
}
else
{
deferred = $q.defer();
promise = deferred.promise;
deferred.resolve();
}
}
catch(error)
{
try{
if (!promise)
{
deferred = $q.defer();
promise = deferred.promise;
}
deferred.reject(error.message);
}
catch(e2){}
}
return promise;
}
在实际应用中运行时,一切正常。尝试为其编写单元测试时出现问题。我有关于何时未启用远程日志记录以及何时发生错误的测试。看起来像这样:
it ("should resolve the promise with nothing when remote logging is turned off", inject(function($rootScope) {
remoteLoggingEnabled = false; //this is declared above a beforeEach that mocks getRemoteLoggingEnabled
var successSpy = jasmine.createSpy("success");
var failSpy = jasmine.createSpy("fail");
var promise = loggingService.callHome("Hello World");
promise.then(successSpy, failSpy);
$rootScope.$digest();
expect(successSpy).toHaveBeenCalledWith(undefined);
expect(failSpy).not.toHaveBeenCalled();
}));
it ("should reject the promise when there is an error with the error message", inject(function($rootScope) {
remoteLoggingEnabled = true;
var successSpy = jasmine.createSpy("success");
var failSpy = jasmine.createSpy("fail");
//angular.toJson is called while it's gathering client-side info
spyOn(angular, "toJson").andCallFake(function() {throw new Error("This is an error");});
var promise = loggingService.callHome("Hello World");
promise.then(successSpy, failSpy);
$rootScope.$digest();
expect(successSpy).not.toHaveBeenCalled();
expect(failSpy).toHaveBeenCalledWith("This is an error");
}));
这些工作很棒。接下来,我想添加针对实际发出请求的时间的测试。我把这样的测试放在一起:
it ("should resolve the promise with the http info when it makes a successful request", inject(function($rootScope, $httpBackend) {
remoteLoggingEnabled = true;
var successSpy = jasmine.createSpy("success");
var failSpy = jasmine.createSpy("fail");
$httpBackend.expect("POST", new RegExp("Logging"), function(jsonStr){
//not concerned about the actual payload
return true;
}).respond(200);
var promise = loggingService.callHome("Hello World");
promise.then(successSpy, failSpy);
$httpBackend.flush();
$rootScope.$digest();
expect(successSpy).toHaveBeenCalledWith(/*http info*/);
expect(failSpy).not.toHaveBeenCalled();
}));
但是,此测试只是挂起。我单步执行代码,并将其卡在
$rootScope.$digest()
的$httpBackend.flush()
调用中,特别是在以下while循环中: while(asyncQueue.length) {
try {
asyncTask = asyncQueue.shift();
asyncTask.scope.$eval(asyncTask.expression);
} catch (e) {
clearPhase();
$exceptionHandler(e);
}
lastDirtyWatch = null;
}
我已经检查了
asyncTask.expression
的循环过程,但是找不到任何正在执行的模式。我仍然对诺言以及如何使用诺言有所了解,所以我希望我在这里所做的根本上是错误的。任何帮助将非常感激。
最佳答案
问题仅出在我的测试设置中(未显示为问题的一部分)。只要出现错误,就会通过修饰的callHome
调用此$exceptionHandler
函数。在callHome
上的测试过程中出现错误,因此再次调用它,然后从那里循环。我修复了该错误,现在一切正常。