1

我需要让我的应用程序使用保存的凭据登录用户并重试 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 拦截器?

4

1 回答 1

3

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

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();

});
于 2014-06-19T15:14:57.497 回答