$ window reize单元测试并应用于其中

时间:2015-08-10 07:00:09

标签: angularjs unit-testing karma-jasmine

我正在尝试测试窗口调整大小但我无法使其工作。如果我使用“createspy bind”模拟该函数而不应用它将起作用。但我想知道是否有更好的方法?

如果我尝试在控制器中使用$scope.$apply,我会收到错误消息:

No more request expected
at $httpBackend (/opt/local/apache2/htdocs/doc/public/lib/angular-mocks/angular-mocks.js:1181)
at sendReq (/opt/local/apache2/htdocs/doc/public/lib/angular/angular.js:8427)
...
at http://localhost:9876/karma.js:182
at http://localhost:9876/context.html:236
undefined

控制器

    var w = angular.element($window);

    w.bind('resize', function () {
      $scope.$apply(function(){
        var windowWidth = parseInt($window.innerWidth,10);
        switch(true){
          case (windowWidth >= 768 && windowWidth < 992):
            $scope.paging.itemsPerPage = 9;
          break;
          default:
            $scope.paging.itemsPerPage = 8;
          break;
        }
      });
    });

测试文件

...

beforeEach(inject(function(){
    spyOn(angular, "element").and.callFake(function () {
        mockWindow = jasmine.createSpy('windowElement');

        mockWindow.bind = jasmine.createSpy('bind').and.callFake(function (evt, fxn) {
            resizeFxn = fxn;                 
        });
        return mockWindow;
    });
}));

...


it('should set paging according to window size', inject(function() {
  expect(mockWindow.bind).toHaveBeenCalledWith("resize", jasmine.any(Function));
  currentWidth = 1;
  resizeFxn();
  expect(scope.paging.itemsPerPage).toBe(8);
}));

0 个答案:

没有答案