简体   繁体   English

Mockjax没有拦截异步表单提交

[英]Mockjax not intercepting async form submission

I'm using qUnit and mockjax to try and handle a simple async form submission but for some reason, the async POST seems to pass through mockjax. 我正在使用qUnit和mockjax尝试处理简单的异步表单提交,但是由于某种原因,异步POST似乎通过了mockjax。

test 'RuleModal closes the modal on a successful form submission event', ->
  $.mockjax
    dataType: 'json'
    url: '/url'
    type: 'post'
    responseText:
      status: 'success'

  $dom = $('<div class="show-modal"><form action="/url" method="post"></form></div>')
  $form = $dom.find('form')
  modal = new RuleModal($dom)

  $form.submit()

  equal $($dom).hasClass('show-modal'), false, 'closes the modal after form submission'

and the implementation 和实施

_bindSubmit: ->
  modal = this

  @$modal.find('form').on 'submit', (event) ->
    event.preventDefault()

    $.ajax
      dataType: 'json'
      url: @action
      type: @method
      data: $(this).serialize()
      success: (data, status, xhr) ->
        modal.close()
      error: (xhr, status, error) ->
        alert 'Something went wrong: ' + error

I tried hardcoding the implementation to match the test exactly but that still didn't work. 我尝试对实现进行硬编码以使其与测试完全匹配,但这仍然行不通。 What am I doing wrong? 我究竟做错了什么?

My guess is that because you do the form submit and then immediately do your assertion that you are running into a race condition. 我的猜测是,因为您进行了表单提交,然后立即做出断言您正在进入竞争状态。 The $form.submit() call is going to execute and still be running when your equal ... line runs. $form.submit()调用将在您的equal ...行运行时执行并仍在运行。 Even though you have mocked out the ajax call, it is still asynchronous. 即使您已经嘲笑了ajax调用,它仍然是异步的。 Unfortunately, the browser native events (like submit ) do not have any kind of callback when they finish, so you may just need a setTimeout() around the assertion: 不幸的是,浏览器本机事件(例如submit )在完成时没有任何回调,因此您可能只需要在断言周围设置setTimeout()

$form.submit();

setTimeout(function() {
    equal($($dom).hasClass('show-modal'), false, 'closes the modal after form submission');
}, 100);  // I think the default in Mockjax is 50ms

That or you could try doing this in an event handler, but that could produce a race condition as well, I think. 那或者您可以尝试在事件处理程序中执行此操作,但是我认为这也可能产生竞争条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM