How do I check Javascript if a form has been submitted?

I am trying to test some of my javascript with Jasmine.

I'm a newbie when it comes to Jasmine and my knowledge of Javascript is basic at best. I want to make it so that the form is submitted. I can't figure out how the syntax of the tests should look like. I guess I need to use spyOn, but I'm not really sure how. I would be very pleased if someone could point me in the right direction.

function submitform(array) {
    var token = array[0].replace("access_token=", "");
    if ((token !== "")) {
        $('input[name=Token]').val(token);
        var frm = document.getElementById("tokenform");
        frm.submit();
    }
}

      

+3


source to share


1 answer


To check that the call has frm.submit()

been called, you have to mock it. There are two ways. The first way will work without changing the code, spying on document.getElementById

, this will work in your example since you only use it once, it will be harder to use document.getElementById

more often.

var submit;
beforeEach(){
  // when your code calls document.getElementById it return an object 
  // with just one property where you can spy on that it was called
  submit = jasmine.createSpy();
  spyOn(document 'getElementById').andReturn({submit:submit})
}

it ("should submit", function(){
  submitform([somedata]);
  expect(submit).toHaveBeenCalled();
})

      



Your best bet is to rewrite your code for better validation. So instead of getting the form by calling the DOM function, insert the form in your function as an argument. Now you can just pass the mock into your function and not mock document.getElementById

. This pattern is also known as Dependency Injection

function submitform(array, frm) {
    var token = array[0].replace("access_token=", "");
    if ((token !== "")) {
        $('input[name=Token]').val(token);
        frm.submit();
    }
}

it ("should submit", function(){
  var submit = jasmine.createSpy();
  var form = {submit: submit}
  submitform([somedata],form);
  expect(submit).toHaveBeenCalled();
})

      

+2


source







All Articles