javascript 如何在 Jasmine 中测试提交的表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7418217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:03:31  来源:igfitidea点击:

How do I test a form submit in Jasmine?

javascriptunit-testingjasmineform-submit

提问by gcdev

I have a form that does some extensive Javascript stuff before finally POSTing to it's ACTION URL. I am writing some Jasmine unit tests and want to make sure the Javascript stuff happens when the form is submitted. However, I definitely don't want the page to go to the ACTION URL while I am unit testing.

我有一个表单,它在最终发布到它的 ACTION URL 之前做了一些广泛的 Javascript 内容。我正在编写一些 Jasmine 单元测试,并希望确保在提交表单时发生 Javascript 内容。但是,当我进行单元测试时,我绝对不希望页面转到 ACTION URL。

I saw what seemed like a good suggestion here: http://groups.google.com/group/jasmine-js/browse_thread/thread/a010eced8db17c1a?pli=1

我在这里看到了一个很好的建议:http: //groups.google.com/group/jasmine-js/browse_thread/thread/a010eced8db17c1a?pli=1

...but, as I am fairly new to Jasmine, I am unsure how to implement it and cannot find any pertinent examples on the web. Does anyone have some sample code I could look at that would accomplish what I need?

...但是,由于我对 Jasmine 相当陌生,我不确定如何实现它,也无法在网络上找到任何相关示例。有没有人有一些我可以查看的示例代码可以完成我的需要?

Thanks!

谢谢!

回答by peekaboo

Maybe this code snippet can help you...

也许这个代码片段可以帮助你......

it('calls ajax post on export button click', function() {
  view.render();
  var form = $('#export_images_xml_form');
  var submitCallback = jasmine.createSpy().andReturn(false);
  form.submit(submitCallback);

  $('#export_images_xml_button').click();

  expect(form.attr('action')).toEqual('/export');
  expect($('#export_images_xml_form input').attr('value')).toEqual('22,33,44');
  expect(submitCallback).toHaveBeenCalled();
});

What I do is basically stopping every submit for given form returning false in the associated callback (see submitCallback behavior).

我所做的基本上是停止给定表单的每次提交,在关联的回调中返回 false(请参阅 submitCallback 行为)。

Then I can also test callback has been called...

然后我还可以测试回调已被调用...

Hope it helps!

希望能帮助到你!

回答by krillgar

If you don't want to test that submitwas called, you don't need to create a spy. With plain jQuery, you can also attain the effect of not submitting the form. I put the following code outside of all tests, that way it applies to all tests within the file.

如果你不想测试submit被调用的,你不需要创建一个间谍。使用普通的jQuery,还可以达到不提交表单的效果。我将以下代码放在所有测试之外,这样它就适用于文件中的所有测试。

$('form').on('submit', function() {
    return false;
});