How to assert a spy is invoked with event on click using jasmine?

后端 未结 2 1915
太阳男子
太阳男子 2021-01-02 02:19

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

Thing = function($){

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


        
2条回答
  •  情歌与酒
    2021-01-02 02:56

    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.

提交回复
热议问题