gpt4 book ai didi

javascript - Rails + Jasmine-Ajax : what is the correct way to test code triggered by `ajax:success` (jquery-ujs)

转载 作者:可可西里 更新时间:2023-11-01 02:48:15 24 4
gpt4 key购买 nike

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

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

<%= link_to 'click here', '/some_path', class: 'special-link', remote: true %>

在库的 JS 部分有事件绑定(bind)代码,这是我想通过它对 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 的影响的正确方法是什么?

最佳答案

您是否试过简单地监视 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

关于javascript - Rails + Jasmine-Ajax : what is the correct way to test code triggered by `ajax:success` (jquery-ujs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36571847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com