title: Mocking the web browser orientationchange event to test bound event handler function with jasmine
body: <p>I have an angularjs directive to create an event handler for the orientation change event to add a classname when the orientation change is landscape (it still needs improvement so bear with me for now):</p>
  
  <pre class="lang-js prettyprint-override"><code>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);
        });
      };
    });
  </code></pre>
  
  <p>Now I would like to test on jasmine such a directive:</p>
  
  <pre class="lang-js prettyprint-override"><code>//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('&lt;div orientation-handler&gt;&lt;/div&gt;');
      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);
    });
  });
  </code></pre>
  
  <p>So, is there a way to programatically trigger the orientation change event, or mocking it somehow to test the bound event handler?</p>
  
  <p>Thanks!</p>