2

Am a newbie in Jasmine. am trying to write a snippet to test my function which is written in jQuery ajax.

Here is the snippet

function submitLoginForm(e){
    e.preventDefault();
    try {
        var data = $("form").serialize();
        $.ajax({
            type: "POST",
            data: data,
            url : "/auth/login",
            dataType: 'json',
            success: function(data){
                submitLoginFormSuccess(data)
            },
            error: function( xhr, status, errorThrown ){
                submitLoginFormError(xhr, status, errorThrown)
            }
        });
    }catch (e) {
        throw new Error(e.message);
    }
}

and the callback functions are

function submitLoginFormSuccess(data){
    if(data.status == "success"){
        window.location = "/app"
    }
    else{
        toastr["error"]("Invalid Credentials!")
    }
}
function submitLoginFormError(xhr, status, errorThrown){
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );
}

Please someone help me.

Issues am getting are;-

  1. event is undefined.

  2. I didn't have any idea how to check success and failure response

Update below snippet is running fine. How should i test other scenerio?

describe("#submitLoginForm", function() {

    it("should make sure that all parameter of ajax is not changed", function() {
      spyOn($, "ajax");
      submitLoginForm(event);
      var result = $.ajax.mostRecentCall.args[0];

      expect(result.url).toEqual("/auth/login");
      expect(result.dataType).toEqual("json");
      expect(result.type).toEqual("POST");

    });

});
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
The Mechanic
  • 2,301
  • 1
  • 26
  • 37
  • 1
    http://stackoverflow.com/questions/4662641/how-do-i-verify-jquery-ajax-events-with-jasmine seems to cover pretty well the different ways of running a unit test on AJAX queries, as well as how to handle this exact type of test. – Daymon Schroeder Sep 17 '15 at 06:03
  • @DaymonSchroeder in my case is not working. Showing me some errors – The Mechanic Sep 17 '15 at 07:33

0 Answers0