Rails + Jasmine-Ajax:测试由`ajax:success`(jquery-ujs)触发的代码的正确方法是什么

Ami*_*itA 10 javascript ajax jquery ruby-on-rails jasmine

我正在尝试测试某个内部库,该库在ajax:success事件上触发了一些JS行为.

该库创建一个如下所示的链接:

<%= link_to 'click here', '/some_path', class: 'special-link', remote: true %>
Run Code Online (Sandbox Code Playgroud)

在库的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
Run Code Online (Sandbox Code Playgroud)

该库在浏览器中按预期工作.但是,当我尝试通过调用在Jasmine中测试库时$('.special-link').click(),无法观察到对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()
Run Code Online (Sandbox Code Playgroud)

测试对ajax:success事件中运行的代码的DOM的影响的正确方法是什么?

Mar*_*nez 1

您是否尝试过简单地监视该ajax功能?为此,您需要使用spyOn并强制它调用success事件处理程序。这将让您测试调用它时您期望发生的情况。

it 'knows how to handle ajax:success events', ->
  spyOn($, "ajax").and.callFake( (e) ->
    e.success({});
  )

  $('.special-link').click()

  # expect some method to be called or something to be changed in the DOM
Run Code Online (Sandbox Code Playgroud)