【问题标题】:unit test for angular responseError interceptor with 'notify' promise带有“通知”承诺的角度响应错误拦截器的单元测试
【发布时间】:2015-01-07 10:51:39
【问题描述】:

我有 angular responseError 拦截器,如果之前的尝试不成功,它会实现向服务器重新发送请求的逻辑。此外,拦截器返回“通知”承诺以保持与当前状态的联系。

return {
        responseError: function(response) {

            var retries = angular.isDefined(response.config.headers['X-RETRIES']) ? response.config.headers['X-RETRIES'] : 0;
            response.config.headers['X-RETRIES'] = retries + 1;

            if (response.config.headers['X-RETRIES'] <= MAX_XHR_ATTEMPTS) {
                var $http = $injector.get('$http'),
                    defer = $q.defer();

                $timeout(function() {
                    defer.notify('trying');
                    defer.resolve($http(response.config));
                }, 1000);

                return defer.promise;

            } else {
                return $q.reject(response);
            }

        }
    };
}

这是一个示例,但它可以正常工作,对于单元测试,我使用 tdd、mocha、chai、sinon。我使用了类似的代码:(拦截器在上面的代码中注入)

test('test', inject(function($http, ) {
        $httpBackend.when('GET', '/test').respond(500);
        var promise = $http.get('/test');

        $httpBackend.flush();
        promise.then(
            function(data) {
                dump('success', data);
            },
            function(data) {
                dump('error', data);
            },
            function(data) {
                dump('notify', data);
            }
        );
    }));

但承诺不会返回任何状态。如果我尝试更改拦截器以在发生错误时返回“拒绝”承诺(没有超时和额外的拉取请求),在这种情况下一切都会按预期工作。案例如何进行测试?

【问题讨论】:

    标签: angularjs unit-testing mocha.js sinon chai


    【解决方案1】:

    您没有刷新 $timeout - 请尝试以下操作:

       test('test', inject(function($http, $timeout) {
            $httpBackend.when('GET', '/test').respond(500);
            var promise = $http.get('/test');
    
            $httpBackend.flush();
            promise.then(
                function(data) {
                    dump('success', data);
                },
                function(data) {
                    dump('error', data);
                },
                function(data) {
                    dump('notify', data);
                }
            );
            // Timeout after we've attached notify listener.
            $timeout.flush(1001);
    
        }));
    

    【讨论】:

    • 谢谢,非常有帮助,它在 $timeout 块中运行 http 请求,但我还无法获得通知承诺 :(
    • 哦,可能是因为我告诉你在添加 then 语句之前执行 $timeout。试试我上面的编辑,之后移动 $timeout 。这使您有机会附加通知回调。由于 promise 被拒绝,您仍然会有错误回调,但 notify 不起作用。查看我的编辑。
    • 我解决了这个问题,谢谢彼得!应该使用$rootScope.$digest() 来发送notify promise,还有一篇我发现了一篇关于测试$timeout 的好文章rudickulous.com/post/75310347493/…
    猜你喜欢
    • 1970-01-01
    • 2018-12-28
    • 2020-04-24
    • 2015-07-30
    • 2014-10-25
    • 2022-10-14
    • 2016-07-25
    • 1970-01-01
    • 2020-10-01
    相关资源
    最近更新 更多