【问题标题】:Testing Angular http interceptor测试 Angular http 拦截器
【发布时间】:2014-06-19 23:14:57
【问题描述】:

我需要让我的应用程序使用保存的凭据登录用户并重试 401 请求,但我很难测试它,因为我需要初始调用返回 401,但之后返回 200登录请求再次发生。

这是我目前的测试:

it("should call login if the status is 401", function() {
  $httpBackend.whenGET(api.baseUrl + "/auth/login").respond(200);
  $httpBackend.whenGET(api.baseUrl + "/practice/active").respond(401);

  api.practiceActiveInquery(function(result) {
    expect(login.fn).toHaveBeenCalled();
  });

  $httpBackend.flush();

});

问题是我需要 /practice/active 的 whenGET 在使用 401 调用一次后以 200 响应,否则我会陷入困境。还是我在考虑如何测试一个完全错误的 http 拦截器?

【问题讨论】:

    标签: angularjs angularjs-http


    【解决方案1】:

    为此,您想使用expectGET 而不是whenGETexpectGET 一次只满足一个请求,因此您可以在每次发出请求时更改响应。像这样的:

    it("should call login if the status is 401", function() {
      $httpBackend.whenGET(api.baseUrl + "/auth/login").respond(200);
      $httpBackend.expectGET(api.baseUrl + "/practice/active").respond(401); //will return 401 the 1st time
      $httpBackend.expectGET(api.baseUrl + "/practice/active").respond(200); //will return 200 the 2nd time
    
      api.practiceActiveInquery(function(result) {
        expect(login.fn).toHaveBeenCalled();
      });
    
      $httpBackend.flush();
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2017-11-07
      • 2018-05-19
      相关资源
      最近更新 更多