【发布时间】:2016-08-02 23:33:48
【问题描述】:
我正在尝试测试某个内部库,该库在ajax:success 事件上触发了一些 JS 行为。
该库创建一个如下所示的链接:
<%= link_to 'click here', '/some_path', class: 'special-link', remote: true %>
在库的JS部分有事件绑定代码,这是我想通过它对DOM的影响进行黑盒测试的部分:
$(document).on 'ajax:success', '.special-link', (e, data, status, xhr) ->
# Code that has some effect on the DOM as a function of the server response
该库在浏览器中按预期工作。但是,当我尝试通过调用 $('.special-link').click() 来测试 Jasmine 中的库时,无法观察到对 DOM 的预期效果。
问题似乎在于ajax:success 事件没有被触发:
describe 'my library', ->
beforeEach ->
MagicLamp.load('fixture') # Fixture library that injects the link above to the DOM
jasmine.Ajax.install()
jasmine.Ajax.stubRequest('/some_path').andReturn({
responseText: 'response that is supposed to trigger some effect on the DOM'})
afterEach ->
jasmine.Ajax.uninstall()
# Works. The fixtures are loading properly
it '[sanity] loads fixtures correctly', ->
expect($('.special-link').length).toEqual(1)
# Works. The jquery-ujs correctly triggers an ajax request on click
it '[sanity] triggers the ajax call', ->
$('.special-link').click()
expect(jasmine.Ajax.requests.mostRecent().url).toContain('/some_path')
# Works. Code that tests a click event-triggering seems to be supported by Jasmine
it '[sanity] knows how to handle click events', ->
spy = jasmine.createSpy('my spy')
$('.special-link').on 'click', spy
$('.special-link').click()
expect(spy).toHaveBeenCalled()
# Does not work. Same code from above on the desired `ajax:success` event does not work
it 'knows how to handle ajax:success events', ->
spy = jasmine.createSpy('my spy')
$('.special-link').on 'ajax:success', spy
$('.special-link').click()
expect(spy).toHaveBeenCalled()
测试在ajax:success事件中运行的代码对DOM的影响的正确方法是什么?
【问题讨论】:
-
我最近回答了类似的问题,这有什么帮助吗? stackoverflow.com/questions/36943055/…
标签: javascript jquery ruby-on-rails ajax jasmine