【问题标题】:Mocking the web browser orientationchange event to test bound event handler function with jasmine使用 jasmine 模拟 Web 浏览器orientationchange 事件以测试绑定的事件处理函数
【发布时间】:2015-01-30 13:22:03
【问题描述】:

我有一个 angularjs 指令来为方向更改事件创建一个事件处理程序,以便在方向更改为横向时添加一个类名(它仍然需要改进,所以暂时请耐心等待):

angular.module('myApp')
  .directive('orientationHandler', function ($rootScope, $timeout, $window) {
    return function(scope, element, attrs) {
      var className = 'mobile_landscape';
      var mediaQuery = 'only screen and (max-width: 768px) and (orientation: landscape)';
      var orientationCheck = function() {
        if ($window.matchMedia(mediaQuery).matches) {
          element.addClass(className);
          $rootScope.$broadcast('Orientation.change', 'landscape');
        } else {
          element.removeClass(className);
          $rootScope.$broadcast('Orientation.change', 'portrait');
        }
      };
      $window.addEventListener('orientationchange', function() {
          $timeout(orientationCheck, 100);
          $timeout(orientationCheck, 200);
        },
        false
      );
      $rootScope.$on('$viewContentLoaded', function() {
        $timeout(orientationCheck, 100);
        $timeout(orientationCheck, 200);
      });
    };
  });

现在我想在 jasmine 上测试这样一个指令:

//TODO: Find a way to test orientation change events
describe('Directive: orientationHandler', function () {

  // load the directive's module
  beforeEach(module('myApp'));

  var element,
      scope,
      $window;

  beforeEach(inject(function ($rootScope, $compile, $httpBackend, _$window_) {
    $window = _$window_;
    scope = $rootScope.$new();
    element = angular.element('<div orientation-handler></div>');
    element = $compile(element)(scope);
    $httpBackend.whenGET(/.*/).respond(200);
  }));

  it('should broadcast an event when changed the orientation', function () {
    var message;
    scope.$on('Orientation.change', function(event, value) {
      message = value;
    });
    angular.element($window).trigger('orientationchange');
    scope.$apply();
    expect(message).toBeDefined();
    expect(angular.isString(message)).toBe(true);
  });
});

那么,有没有办法以编程方式触发方向更改事件,或者以某种方式模拟它以测试绑定的事件处理程序?

谢谢!

【问题讨论】:

    标签: javascript unit-testing angularjs-directive jasmine orientation-changes


    【解决方案1】:

    几点:

    1. 我会使用以下方法来检查方向的类型:

      $window.screen.orientation.type
      

      无需运行媒体查询。

    2. 我使用以下方法在我的测试中触发事件:

      function dispatchOrientationChangeEvent() {
        var evt, orientationEventType = 'orientationchange';
        evt = $window.document.createEvent('HTMLEvents');
        evt.initEvent(orientationEventType, true, true);
        $window.dispatchEvent(evt);
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多