如何防止 angular 拦截器在茉莉花测试期间获取 $httpBackend 响应

How to prevent angular interceptors from picking up $httpBackend responses during jasmine test

我在我的 angular 应用程序中为我的登录控制器编写测试,在 "login fails with invalid credentials" 测试期间,API returns 一个 401。问题是auth 拦截器(其工作是获取 401),进行干预并尝试执行未正确注入的依赖项。

拦截器是如何注入我的 app.js:

$httpProvider.interceptors.push('authInterceptor');

这是拦截器的内部结构(它是一个工厂):

return {
    response: function(response){
        return response || $q.when(response);
    },
    responseError: function(rejection) {
        if (rejection.status === 401 && $location.path() !== '/login') {
            // Clear user state.
            delete $rootScope.loggedUser;
            storage.clearAll();
            document.cookie = "my_session=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

            // Redirect.
            $location.path("/login");
        }
        return $q.reject(rejection);
    }
}

这是我的测试(运行 针对登录控制器,而不是上面的拦截器。理想情况下,拦截器甚至不应该在此测试用例中执行):

it('should fail with invalid credentials', inject(function($httpBackend, $location, storage) {
    $httpBackend.expectPOST('/api/login').respond(401);
    scope.loginCredentials = {email : 'email@email.com', password : 'password'};
    scope.login(scope.loginCredentials);
    $httpBackend.flush();
}));

我的存储库模拟是这样注入的-

var LoginCtrl,
    mockStorage,
    store,
    scope;

// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, storage, User) {
    scope = $rootScope.$new();
    store = [];

    mockStorage = storage;
    spyOn(mockStorage,'get').andCallFake(function(key){
        return store[key];
    });
    spyOn(mockStorage,'set').andCallFake(function(key, val){
        store[key] = val;
    });

    LoginCtrl = $controller('LoginCtrl', {
        $scope: scope,
        $rootScope: $rootScope,
        storage: mockStorage,
        User: User
    });
}));

问题是测试中的模拟存储库没有被拦截器调用,而是试图注入真实的存储库,但没有成功,导致库出现内部错误:

TypeError: Cannot read property 'clear' of undefined
    at Object.publicMethods.clearAll (/path/to/app/ui/app/bower_components/ngStorage/src/angularLocalStorage.js:178:12)

有什么建议吗?谢谢

参见this answer。您需要用模拟的服务覆盖真实的存储服务:

  module(function ($provide) {
      $provide.value('storage', mockStorage);
  });