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

前端之家收集整理的这篇文章主要介绍了javascript – Rails Jasmine-Ajax:测试由’ajax:success`(jquery-ujs)触发的代码的正确方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图测试某个内部库,它有一些在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中运行的代码的DOM的影响的正确方法是什么:成功事件?

解决方法

你试过简单的监视ajax的功能吗?为此,您需要使用spyOn并强制它调用成功事件处理程序.这将让你测试你期望发生什么,当它被调用.
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
原文链接:https://www.f2er.com/ajax/153706.html

猜你在找的Ajax相关文章