【问题标题】:How to test an error response in angular's $httpBackend?如何在 Angular 的 $httpBackend 中测试错误响应?
【发布时间】:2015-11-05 17:46:05
【问题描述】:

我们使用的是 Angular 1.2.x(由于 IE8,我们必须这样做)。我们正在测试 Karma 和 Jasmine。我想测试我的模块的行为,以防服务器响应错误。根据角度文档,我应该像这样简单地准备 $httpBackend 模拟(正如我所期望的那样):

authRequestHandler = $httpBackend.when('GET', '/auth.py');

// Notice how you can change the response even after it was set
authRequestHandler.respond(401, '');

这就是我在测试中所做的:

beforeEach(inject(function($injector) {
    keepSessionAliveService = $injector.get('keepSessionAliveService');
    $httpBackend = $injector.get('$httpBackend');
    $interval = $injector.get('$interval');
}));

(...)

describe('rejected keep alive request', function() {
    beforeEach(function() {
        spyOn(authStorageMock, 'get');
        spyOn(authStorageMock, 'set');

        $httpBackend.when('POST', keepAliveUrl).respond(500, '');

        keepSessionAliveService.start('sessionId');
        $interval.flush(90*60*1001);
        $httpBackend.flush();
    });

    it('should not add the session id to the storage', function() {
        expect(authStorageMock.set).not.toHaveBeenCalled();
    });
});

但是测试失败了,因为正在调用模拟函数,我可以在代码覆盖率中看到它永远不会遇到我传递给 §promise.then 作为第二个参数的错误函数。

显然我在这里做错了什么。它是否必须与我们使用的旧 Angular 版本有关?

任何帮助将不胜感激!

【问题讨论】:

    标签: angularjs jasmine karma-runner angular-mock


    【解决方案1】:

    类似这样的:

       it("should receive an Ajax error", function() {
            spyOn($, "ajax").andCallFake(function(e) {
                e.error({});
            });
    
             var callbacks = {
                displayErrorMessage : jasmine.createSpy()
            };
    
            sendRequest(callbacks, configuration);
            expect(callbacks.displayErrorMessage).toHaveBeenCalled();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2013-07-25
      • 2018-02-12
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      相关资源
      最近更新 更多