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

后端 未结 2 1901
太阳男子
太阳男子 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.

    0 讨论(0)
  • 2021-01-02 03:10

    If you can't use jQuery you may use dispatchEvent and check its return value (based on this answer).

    const domElem = document.getElementById('some_dom_element');
    const clickEvent = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true
    });
    
    const cancelled = !domElem.dispatchEvent(clickEvent);
    expect(cancelled).toBeTruthy();
    
    0 讨论(0)
提交回复
热议问题