简体   繁体   中英

Unit-testing javascript/jQuery events with Jasmine

I have this code:

$(document).on('click', '#clear-button', clearCalculatedPrice)

clearCalculatedPrice = ->
    $('#price_rule').removeAttr('data-original-title')
    $('#calculated-price').removeAttr('data-original-title')
    $('#calculated-price').empty()

And such test for it

describe 'Call taker', ->
  it 'should clear calculated price', ->
    spyOn($.fn, 'removeAttr')
    spyOn($.fn, 'empty')
    clearCalculatedPrice()
    expect($.fn.removeAttr).toHaveBeenCalled()
    expect($.fn.empty).toHaveBeenCalled()

I need to create another test which will check that function was called when event was triggered, like this

     it 'should clear calculated price when "click" event is triggered', ->
      $('#destination-clear-button').trigger('click')
      spyOn($.fn, 'removeAttr')
      spyOn($.fn, 'empty')
      expect($.fn.removeAttr).toHaveBeenCalled()
      expect($.fn.empty).toHaveBeenCalled()

But this test do not work as I thought. So question is: How should unit-test that tests event handler should be written

Probably order calls is bad

 it 'should clear calculated price when "click" event is triggered', ->
  # set spys
  spyOn($.fn, 'removeAttr')
  spyOn($.fn, 'empty')
  # trigger
  $('#destination-clear-button').trigger('click')
  # check
  expect($.fn.removeAttr).toHaveBeenCalled()
  expect($.fn.empty).toHaveBeenCalled()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM