[英]How to test document.addEventListener('keydown', cb) with Mocha & Sinon?
I'm trying to figure out the best way for testing this method:我试图找出测试此方法的最佳方法:
document.addEventListener("keydown", function (event) {
var modifiers = event.altKey || event.ctrlKey || event.metaKey ||
event.shiftKey;
var mapped = map[event.which];
if (!modifiers) {
if (mapped !== undefined) {
event.preventDefault();
self.emit("move", mapped);
}
}
});
I'd like to ensure that if the keys are modifiers or if the keys are not mapped, nothing happens, however, if they are, to spy on the self.emit
function.我想确保如果键是修饰符或者键未映射,则不会发生任何事情,但是,如果是,则监视self.emit
函数。
I could do it with sinon.我可以用sinon做到这一点。 Here is my solution:这是我的解决方案:
it('adds listener events', function() {
sinon.spy(document, 'addEventListener')
sinon.spy(window, 'addEventListener')
expect(document.addEventListener.calledOnce).not.to.be.true
expect(window.addEventListener.calledOnce).not.to.be.true
subject.myFunc()
expect(document.addEventListener.calledOnce).to.be.true
expect(window.addEventListener.calledOnce).to.be.true
})
In my case I had to test window focus
and document click
for example.在我的例子中,我不得不测试窗口focus
和文档click
。
Hope it helps希望它有帮助
Try this.试试这个。
before(function() {
// Create stubs to spy on calls without executing the native code
global.document= {addEventListener: sinon.stub()};
global.self = {emit: sinon.stub()};
// Execute the function under test
subject.myFunc();
// Save the callback function
this.callback = document.addEventListener.getCalls()[0].args[1];
this.eventType = document.addEventListener.getCalls()[0].args[0];
});
it('should use appropriate arguments', function() {
this.eventType.should.eql("keydown");
this.callback.should.be.a("function");
});
it('should use a callback that does nothing without a modifier key', function() {
const eventProxy = {
which: 97, // "A"
preventDefault: sinon.stub()
};
this.callback(eventProxy);
eventProxy.preventDefault.should.not.be.called;
global.self.emit.should.not.be.called;
});
it('should use a callback that prevents default with a modifier key', function() {
const eventProxy = {
which: 97, // "A"
shiftKey: true,
preventDefault: sinon.stub()
};
this.callback(eventProxy);
eventProxy.preventDefault.should.be.calledOnce.and.calledWith();
global.self.emit.should.be.calledOnce.and.calledWith('move');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.