AngularJS :测试 returns 承诺的工厂,同时模拟使用 $http 的服务

AngularJS : testing a factory that returns a promise, while mocking a service that uses $http

我有一个服务具有以下方法(以及其他方法),其中 returns 一个 $http 承诺

  function sessionService($http, serviceRoot) {
    return {
        getAvailableDates: function () {
            return $http.get(serviceRoot + '/session/available_dates');
        }
    };
  };

  angular.module('app').service('sessionService', ['$http', 'serviceRoot', sessionService]);

然后另一个工厂将它和 caches/adds 数据包装到 localStorage。这returns一个常规的承诺

angular.module('app')
    .factory('AvailableDates', AvailableDates);

AvailableDates.$inject = ['sessionService', '$window', '$q'];

function AvailableDates(sessionService, $window, $q) {
    var availableDates = [];

    return {
        getAvailableDates: getAvailableDates
    };

    function getAvailableDates() {
        var deferred = $q.defer();
        var fromStorage = JSON.parse($window.sessionStorage.getItem('validDates'));

        if (availableDates.length > 0) {
            deferred.resolve(availableDates);
        } else if (fromStorage !== null) {
            deferred.resolve(fromStorage);
        } else {
            sessionService.getAvailableDates()
                .success(function (result) {
                    availableDates = result;
                    $window.sessionStorage.setItem('validDates', JSON.stringify(availableDates));
                    deferred.resolve(availableDates);
                });
        }
        return deferred.promise;
    }
}

一切正常。我的问题是我不知道如何在模拟 sessionService 时测试这个东西。我已经阅读了所有相关的 Whosebug 问题,并尝试了各种不同的方法,但无济于事。

这是我的测试目前的样子:

describe('testing AvailableDates factory', function () {
    var mock, service, rootScope, spy, window, sessionStorageSpy, $q;
    var dates = [ "2014-09-27", "2014-09-20", "2014-09-13", "2014-09-06", "2014-08-30" ];
    var result;

    beforeEach(module('app'));

    beforeEach(function() {
        return angular.mock.inject(function (_sessionService_, _AvailableDates_, _$rootScope_, _$window_, _$q_) {
            mock = _sessionService_;
            service = _AvailableDates_;
            rootScope = _$rootScope_;
            window = _$window_;
            $q = _$q_;
        });
    });

    beforeEach(inject(function () {
        // my service under test calls this service method
        spy = spyOn(mock, 'getAvailableDates').and.callFake(function () {
            return {
                success: function () {
                    return [ "2014-09-27", "2014-09-20", "2014-09-13", "2014-09-06", "2014-08-30" ];
                },
                error: function() {
                    return "error";
                }
            };
        });

        spyOn(window.sessionStorage, "getItem").and.callThrough();
    }));

    beforeEach(function() {
        service.getAvailableDates().then(function(data) {
            result = data;
            // use done() here??
        });
    });

    it('first call to fetch available dates hits sessionService and returns dates from the service', function () {
        rootScope.$apply(); // ??

        console.log(result); // this is printing undefined

        expect(spy).toHaveBeenCalled();  // this passes
        expect(window.sessionStorage.getItem).toHaveBeenCalled(); // this passes
    });
});

我尝试了各种方法,但无法弄清楚如何测试 AvailableDates.getAvailableDates() 调用的结果。当我使用 done() 时,出现错误: 超时 - 未在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内调用异步回调(我尝试覆盖此值,但不走运)。

如果我取出 done(),并在调用 .then 之后调用 rootScope.$apply(),我将得到一个未定义的值作为结果。

我做错了什么?

我在你的示例中发现了更多问题。

主要问题是模拟中的成功定义。 Success是一个函数,它有一个函数作为参数——回调。收到数据时调用回调 - 数据作为第一个参数传递。

return {
    success: function (callback) {
        callback(dates);
    }
};

这里是简化的工作示例http://plnkr.co/edit/Tj2TZDWPkzjYhsuSM0u3?p=preview

在这个例子中,mock 被传递给具有模块函数的提供者(来自 ngMock)——您可以传递带有键(服务名称)和值(实现)的对象。该实现将用于注入。

module({
      sessionService:sessionServiceMock
});

我认为测试逻辑应该在一个函数(测试)中,将其拆分为beforeEach和测试不是一个好的解决方案。测试是我的榜样;它更具可读性,并且具有清晰分离的部分 - 安排、行动、断言。

inject(function (AvailableDates) {
    AvailableDates.getAvailableDates().then(function(data) {
      expect(data).toEqual(dates);
      done();
    });

    rootScope.$apply(); // promises are resolved/dispatched only on next $digest cycle

    expect(sessionServiceMock.getAvailableDates).toHaveBeenCalled();
    expect(window.sessionStorage.getItem).toHaveBeenCalled();
  });