我的 jasmine 套件和 jQuery 的新事件注册方法 .on() 的使用有问题。
这是我的夹具的简化版本:
<div id='rent_payment_schedule_container'>
<select class="select optional" id="frequency_select" name="payment_schedule[frequency]">
<option value="0">Monthly</option>
<option value="1">Weekly</option>
<option value="2">Bi-Weekly</option>
</select>
<div class="control-group select optional start-day-select" id="monthly_select"></div>
<div class="control-group select optional start-day-select" id="weekly_select" style="display: none;"></div>
</div>
这是咖啡脚本(在使用它的实际页面上工作得很好):
$ ->
$('#rent_payment_schedule_container').on 'change', '#frequency_select', (event) ->
$('.start-day-select').hide()
switch $(event.target).val()
when '0'
$('#monthly_select').show()
when '1'
$('#weekly_select').show()
when '2'
$('#weekly_select').show()
这是规格:
describe 'The UI components on the payment schedule creation page', ->
beforeEach ->
loadFixtures 'payment_schedule'
describe 'The toggling of the monthly and weekly day select options', ->
it 'shows the weekly select div and hides the monthly select div when the weekly option is selected from the #frequency_select select box', ->
$('#frequency_select option[value=1]').attr('selected', 'selected')
$('#frequency_select').change()
expect($("#weekly_select")).toBeVisible()
it 'shows the weekly select div and hides the monthly select div when the bi-weekly option is selected from the #frequency_select select box', ->
$('#frequency_select option[value=2]').attr('selected', 'selected')
$('#frequency_select').change()
expect($("#weekly_select")).toBeVisible()
it 'shows the monthly select div and hides the weekly select div when the monthly option is selected from the #frequency_select select box', ->
$('#frequency_select option[value=1]').attr('selected', 'selected')
$('#frequency_select').change()
$('#frequency_select option[value=0]').attr('selected', 'selected')
$('#frequency_select').change()
expect($("#monthly_select")).toBeVisible()
而且每次都惨败。
但是,如果我不用$('#rent_payment_schedule_container')
作 的接收器.on()
,而是使用$(document)
,那么整个事情就很好了。
$ ->
$(document).on 'change', '#frequency_select', (event) ->
$('.start-day-select').hide()
switch $(event.target).val()
when '0'
$('#monthly_select').show()
when '1'
$('#weekly_select').show()
when '2'
$('#weekly_select').show()
所以,我最好的猜测是,这与 jasmine 加载夹具然后运行测试的方式的顺序或速度有关,但我不能确定。谁能指出我正确的方向,为什么会发生这种情况以及如何解决?