如何模拟$ window单元测试AngularJS服务?

时间:2014-05-18 06:23:26

标签: angularjs unit-testing jasmine karma-runner

这是我的服务:

var services = angular.module('amdotcom.services', ['ngResource']);

services.factory('homePageRes', ['$resource', '$window',
    function ($resource, $window) {
       var wdw = angular.element($window);
       return $resource('home/index', {
           height: wdw.height(),
           width: wdw.width()
       });
   }]);

services.factory('homePageLoader', ['homePageRes', '$q',
  function (homePageRes, $q) {
      return function () {
          var delay = $q.defer();
          homePageRes.get(function (homePage) {
              delay.resolve(homePage);
          }, function () {
              delay.reject('Unable to fetch home page');
          });
          return delay.promise;
      };
  }]);

以下是我在介绍$ window服务之前的测试。这些测试工作正常,但是一旦我介绍了$ window服务,我就无法嘲笑它。

describe('Services', function () {

    beforeEach(function () {
        module("amdotcom.services");
    });

    describe('homePageLoader', function () {
        var mockBackend, loader;

        beforeEach(inject(function ($httpBackend, homePageLoader) {
            mockBackend = $httpBackend;
            loader = homePageLoader;
        }));

        it('should return home page information', function () {
            mockBackend.expectGET('home/index?height=400&width=500').respond({ "Albums": [{ "Id": 2, "Name": "best shots" }] });

            var homePageData;

            var promise = loader();
            promise.then(function (homePg) {
                homePageData = homePg;
            });

            expect(homePageData).toBeUndefined();

            mockBackend.flush();

            expect(homePageData.Albums[0].Id).toEqual(2);
            expect(homePageData.Albums[0].Name).toEqual("best shots");
        });

        afterEach(function () {
            mockBackend.verifyNoOutstandingExpectation();
            mockBackend.verifyNoOutstandingRequest();
        });
    });
});

我收到的错误是:TypeError:' undefined'不是一个功能(评估' wdw.height()')

我尝试使用$ provider和spyOn方法,但都没有。请帮忙。

阿伦

1 个答案:

答案 0 :(得分:6)

显然,height()和width()函数不正确。我将它们更改为innerHeight和innerWidth属性。

services.factory('homePageRes', ['$resource', '$window',
    function ($resource, $window) {
       return $resource('home/index', {
           height: $window.innerHeight,
           width: $window.innerWidth
       });
    }]);

beforeEach(function () {
    angular.mock.module("amdotcom.services", function ($provide) {
        var myMock = {
            innerHeight: 400,
            innerWidth: 500
        };
        $provide.value('$window', myMock);
    });
});

由于我上面的评论没有格式化且可读性较差,我已在此处再次添加。