javascript 在 Jasmine 中测试自定义事件的处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17264376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing the handling of a custom event in Jasmine
提问by joecritch
I am wanting to ensure that a object's method gets called as an event handler, when a custom jQuery event is triggered; but the unit test is seemingly returning a false-negative, as my implementation works well.
我想确保在触发自定义 jQuery 事件时将对象的方法作为事件处理程序调用;但是单元测试似乎返回了一个假阴性,因为我的实现效果很好。
(This is part of a test suite that uses Twitter Flight& the Flight Jasmine extensions, but this is just a vanilla Jasmine spy.)
(这是使用Twitter Flight和Flight Jasmine 扩展的测试套件的一部分,但这只是一个普通的 Jasmine 间谍。)
describe('listening for uiNeedsPlan event', function() {
var spy;
beforeEach(function() {
spy = spyOn(this.component, 'getPlan');
$(document).trigger('uiNeedsPlan');
});
it('gets the current plan', function() {
expect(spy).toHaveBeenCalled();
});
});
This results in a failed spec:
这导致规范失败:
Expected spy getPlan to have been called.
Expected spy getPlan to have been called.
Here is a snippet from my code implementation of my Flight component (which works successfully):
这是我的 Flight 组件(成功运行)的代码实现中的一个片段:
this.after('initialize', function () {
this.on(document, 'uiNeedsPlan', this.getPlan);
});
回答by Tom Hamshere
Before I go in to the details of why this isn't working, I'd first like to point out that it's bad practice to test whether this method has been executed. You should be testing the component's interface - its input and output and its effect on the DOM. How it does what it does (which internal methods it calls, its internal state) is irrelevant.
在我详细说明为什么这不起作用之前,我首先想指出测试此方法是否已执行是不好的做法。您应该测试组件的接口 - 它的输入和输出以及它对 DOM 的影响。它如何做它所做的(它调用哪些内部方法,它的内部状态)是无关紧要的。
As to why it's not working: When you create the spy, you are spying on the unbound version of the component method. When the component is instantiated, methods are bound to the instance and assigned to callbacks. It is impossible (afaik) to access these bound methods after the component is instantiated.
至于为什么它不起作用:当您创建间谍时,您正在监视组件方法的未绑定版本。当组件被实例化时,方法被绑定到实例并分配给回调。在实例化组件后,不可能(afaik)访问这些绑定方法。
Instead, you need to spy on the the prototype before the component instance is attached to the DOM. Also, you don't seem to be calling setupComponent at all, so this.component won't exist yet anyway.
相反,您需要在组件实例附加到 DOM 之前监视原型。此外,您似乎根本没有调用 setupComponent,因此无论如何 this.component 都不存在。
var spy;
beforeEach(function () {
spy = spyOn(this.Component, 'getPlan');
setupComponent();
$(document).trigger('uiNeedsPlan');
});
it('executes getPlan', function() {
expect(spy).toHaveBeenCalled();
});