title: Simulate fake keypress in jasmine
body: <p>I'm trying to simulate a keypress in Jasmine (the test browser is PhantomJS) so I can unit test some of my functions that use key presses. Unfortunately, I can't test it properly with Jasmine because I'm getting errors.</p>
  
  <p>Here's the code I'm trying to test:</p>
  
  <pre><code>function Controls() {
    'use strict';
    this.codes = {
      37: 'left',
      39: 'right',
      38: 'forward',
      40: 'backward'
    };
    this.states = {
      'left': false,
      'right': false,
      'forward': false,
      'backward': false
    };
    document.addEventListener('keydown', function() { this.onKey.bind(this, true); }, false);
    document.addEventListener('keyup', function() { this.onKey.bind(this, false); }, false);
  }
  
  Controls.prototype.onKey = function(val, e) {
    var state = this.codes[e.keyCode];
  
    if (typeof state === 'undefined') return false;
  
    this.states[state] = val;
  
    // Stop the key press from repeating
    e.preventDefault();
    e.stopPropagation();
  
    return true;
  };
  
  controls = new Controls();
  </code></pre>
  
  <p>(NOTE: The above code wraps the functions in the addEventListener with anon functions so that Jasmine will actually attempt to run my tests. Without the anonymous wrap, this results in another error: <code>TypeError: 'undefined' is not a function (evaulating 'this.onKey.bind(this, true)'</code> Solving this problem would be great too.
  )</p>
  
  <p>And this is my attempt at testing:</p>
  
  <pre><code>function keyPress(key) {
    var pressEvent = document.createEvent('KeyboardEvent');
    pressEvent.initKeyEvent('keydown', true, true, window,
                              false, false, false, false,
                              0, key);
    document.dispatchEvent(pressEvent);
  }
  
  describe("Controls", function() {
    var controls;
  
    it("should initialize properly", function() {
      controls = new Controls();
      expect(controls).not.toBe(null);
    });
  
    it("should reflect changes in state when arrow keys are used", function() {
      keyPress(37);
      expect(controls.states[state]).toBe(37);
    });
  });
  </code></pre>
  
  <p>This results in an error from Jasmine:</p>
  
  <pre><code>TypeError: 'undefined' is not a function (evaluating 'pressEvent.initKeyEvent('keydown', true, true, window, false, false, false, false, 0, key)')
  </code></pre>
  
  <p>I'm still very new to Jasmine (and for that matter, Javascript), so any help in general would be appreciated.</p>