【发布时间】:2015-07-06 14:39:07
【问题描述】:
我正在尝试在 Angular 中测试使用 $http 的服务,但大约 5 秒后(茉莉花超时)我得到:
错误:超时 - 在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内未调用异步回调。
错误:超时 - 在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内未调用异步回调。
我尝试过使用 $rootScope.$digest(),但这似乎没有任何区别。测试(和应用程序代码)是用 Typescript 编写的,代码在实际应用程序中运行良好。
我没有看到提示 then() 已运行的警报/日志,但我确实设法在测试中使用 setTimeout() 发出警报(没有应用程序更改),但我仍然遇到错误。
测试代码
var $httpBackend, orderSearchService;
beforeEach(inject((_$httpBackend_, _orderSearchService_) => {
$httpBackend = _$httpBackend_;
orderSearchService = _orderSearchService_;
$httpBackend.expectGET("http://testUrl/api/search/testquery");
$httpBackend.whenGET("http://testUrl/api/search/testquery").respond(200, "testData");
}));
it("can call $http and retrieve results",(done) => {
orderSearchService.search("testquery").then(promise => {
var results = promise.data;
alert(results);
expect(results).toBe("testData");
$httpBackend.flush();
done();
});
});
服务摘录:
public search(term: string): angular.IPromise<any> {
var result: angular.IPromise<any> = this.httpService.get("http://testUrl" + "/api/search/" + term)
.success((data: any) => { return data });
return result;
}
我的理解是测试应该调用search(),Jasmine应该等待done()被调用。
【问题讨论】:
-
您已跳过在单元测试中调用
$digest()方法。 Angular 不知道何时执行.then()方法
标签: angularjs unit-testing asynchronous jasmine