angularjs - 单元测试,当 $http 没有被调用时等待 promise

标签 angularjs unit-testing promise

我有一个单元测试,其中服务返回一个 promise 。有时该服务可能会发出 $http 请求,有时不会(它实现了某种缓存)。无论哪种情况,它都会解决 promise ,但只有在 $httpBackend.flush() 中它才真正开始进行回调。我怎样才能使已解析的 promise 像flush()那样实际调用.then()中的函数。

这个效果很好

resolved = jasmine.createSpy();
rejected = jasmine.createSpy();
employeeEventService.loadSchedules()
    .then(resolved, rejected);

$httpBackend.flush();  // This causes the promise to resolve/reject

expect(resolved).toHaveBeenCalled();
expect(rejected).not.toHaveBeenCalled();

这个不起作用,因为我无法调用flush()(因为该服务从未调用过$http)

resolved = jasmine.createSpy();
rejected = jasmine.createSpy();
employeeEventService.loadSchedules()
    .then(resolved, rejected);

//$httpBackend.flush();  // Can't call this because this call is "cached"

expect(resolved).toHaveBeenCalled();
expect(rejected).not.toHaveBeenCalled();

服务代码:

if(loaded.startOn <= params.startOn && loaded.endOn >= params.endOn
   && new Date() - lastFetch < 60000) {
     deferred.resolve(loaded.schedules);
} else {
    service.loading +=1;
    config = {params: params, timeout:30*1000};
    $http.get('/api/employee-schedules/', config)
        .then(function(response) {
            ...
            process the json response
            ...
            deferred.resolve(loaded.schedules);
         }, function(reason, status) {
            $log.error("Failed to get schedules", reason, status);
            deferred.reject(reason, status);
         })
         .finally(function() {
              service.loading -=1;
         });
}
return deferred.promise;

最佳答案

所有的 promise ,无论它们采用什么模式,都会在您调用 $scope.$digest(); 时得到解析

关于angularjs - 单元测试,当 $http 没有被调用时等待 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22888960/

相关文章:

javascript - 什么是 $$hashKey 添加到我的 JSON.stringify 结果

unit-testing - 使用 Link 测试 React Router

javascript - 在给定场景中实现 promise 的最佳方式是什么?

javascript - Bluebird 对一系列功能的 promise

javascript - 测试 commonjs 模块的替代方案是什么?

javascript - 使用 NODE JS 和 BLUEBIRD 从 REDIS 中获取数据

javascript - 带有 ng-repeat 的 AngularJS 依赖下拉菜单

javascript - 在 ui-router 中保持 onExit

php - JavaScript 促进了 OpenID 登录?

angular - 如何使用 Injector 在函数中模拟注入(inject)的服务