Yasemin'de bir tuşa basmaya çalışıyorum (test tarayıcısı PhantomJS), bu nedenle tuş basımlarını kullanan bazı işlevlerimi birimden test edebilirim. Maalesef, Jasmine ile düzgün bir şekilde test edemiyorum çünkü hata alıyorum. İşte Yasemin'de sahte tuşa basma benzetimi
kod Testten çalışıyorum oluyor: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();
(NOT:. Yasemin aslında benim testler dener böylece Yukarıdaki kod anonim olmadan anon fonksiyonları ile addEventListener fonksiyonlarını sarar . TypeError: 'undefined' is not a function (evaulating 'this.onKey.bind(this, true)'
Bu sorunu çözmek çok iyi olurdu )
Ve bu test benim girişimi: sarma, bu başka hata ile sonuçlanır
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);
});
});
Bu Jasmine gelen hatayla sonuçlanır:
TypeError: 'undefined' is not a function (evaluating 'pressEvent.initKeyEvent('keydown', true, true, window, false, false, false, false, 0, key)')
Hala Jasmine'e çok yeniyim (ve bu konuda, JavaScript için), bu yüzden genel olarak herhangi bir yardım mutluluk duyacağız.
Bu, asıl meseleyi çözdüğü için, bu cevabı kabul ettim; teşekkürler Chris! Ancak, asıl sorum gerçekten sormam gereken şey değildi, bu yüzden aşağıda daha fazla ayrıntı vereceğim. – emmabukacek
Merhaba, Bu eski bir yazıdır, ancak '' '' keyCode''' artık kullanımdan kaldırılmıştır [MDN makalesine bakın] (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode). Bu nedenle, kod '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' 'yi kullanmalı ve böylece biraz farklı olmalıdır. – ollie314