我正在尝试模拟Jasmine中的按键(测试浏览器是PhantomJS),因此我可以对使用按键的一些功能进行单元测试.不幸的是,我无法使用Jasmine正确测试它,因为我遇到了错误.
这是我要测试的代码:
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 …Run Code Online (Sandbox Code Playgroud)