2014-06-19 141 views
1

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

这是到目前为止我的测试:

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

}); 

的问题是我需要/实习/主动与200回应的whenGET它与401调用一次后,或者​​我被逮住了一圈。或者我在想如何测试一个完全错误的http拦截器?

回答

3

为此,您要使用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(); 

});