How do I test a form submit in Jasmine?

gcdev picture gcdev · Sep 14, 2011 · Viewed 17.4k times · Source

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.

I saw what seemed like a good suggestion here: 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?

Thanks!

Answer

peekaboo picture peekaboo · Nov 7, 2011

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).

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

Hope it helps!