使用jasmine点击事件调用如何断言间谍? [英] How to assert a spy is invoked with event on click using jasmine?

查看:230
本文介绍了使用jasmine点击事件调用如何断言间谍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个简单的点击处理程序,需要传入的事件(如此)

I'm writing a simple click handler and need the event passed in (like so)

Thing = function($){

    var MyObject = function(opts){
        this.opts = opts;
    };

    MyObject.prototype.createSomething = function(){
        var that = this;
        $('#some_dom_element').live('click', function(e) {
            that.doStuff(e);
        });
    };

    MyObject.prototype.doStuff = function(e) {
        //do some javascript stuff ...
        e.preventDefault();
    };

    return MyObject;

}(jQuery);

目前在我的茉莉花规格中,我有一些东西要监视我希望被调用的函数(但是因为它用e -not调用而没有args-我的断言失败了)

Currently in my jasmine spec I've got something to spy on the function I expect gets invoked (but since it's called with e -not without args- my assertion is failing)

    it ("live click handler added to the dom element", function(){
        var doSpy = spyOn(sut, 'doStuff');
        sut.createSomething();
        $("#some_dom_element").trigger('click');
        expect(doSpy).toHaveBeenCalledWith();
    });

如何纠正这个toHaveBeenCalledWith按照我的预期工作?

How can I correct this "toHaveBeenCalledWith" to work as I expect?

更新

我无法得到接受的答案按原样工作,但我能够稍微修改它,以下是我100%工作的例子

I couldn't get the accepted answer to work as is but I was able to alter it just a little and the below is my 100% working example

    it ("should prevent default on click", function(){
        var event = {
            type: 'click',
            preventDefault: function () {}
        };
        var preventDefaultSpy = spyOn(event, 'preventDefault');
        sut.createSomething();
        $("#some_dom_element").trigger(event);
        expect(preventDefaultSpy).toHaveBeenCalledWith();
    });


推荐答案

你必须触发自己的事件通过间谍 stopPropagation 方法,因为你想测试事件是否已经停止。

You have to trigger your own event passing a spy for the stopPropagation method, cause you wanna test if the event was stopped.

var event = {
    type: 'click',
    stopPropagation: function(){}
}
var spy = spyOn(event, 'stopPropagation');
$('#some_dom_element').trigger(event);
expect(spy).toHaveBeenCalled();

注意:当您监视要测试的对象时会有代码味道,因为您开始测试你班级的内在行为。把你的功能想象成一个黑盒子,只测试你投入的东西并离开。在您的情况下,重命名函数将破坏测试,而代码仍然有效。

Note: there is code smell when you spy on the object you want to test, because you start to test the inner behavior of your class. Think about your function as a black box and test only the things you put in and get out. In your case, renaming the function in will break the test, while the code is still valid.

这篇关于使用jasmine点击事件调用如何断言间谍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆