0

I have a JS function I'll call myPost that basically just wraps around a $.ajax function that passes an object containing the params and methods. I have searched extensively for examples of writing Mocha tests using Chai and Sinon for this situation but so far have not found any. I'm fairly new to writing unit tests and would like some help on this.

My function to test:

const post_login = (username, pword) => {

  $.ajax({
    type: 'POST',
    url: './path/to/Security.cfc',
    dataType: 'JSON',
    data: {
        'method':'postLogin',
        'uname': (username),
        'pword': (pword)
    },
    success: function(response, status, jqXHR) {
      if(response.ERROR.length) {
        $("#submitResponse").html("There was a problem... " + response.ERROR).show();
      }
      else {
        // now clear out the input fields
        $("#inputUserName").val('');
        $("#inputPassword").val('');

        // set data attr for logged in ok and change page content displayed
        $('#login').attr('data-logged', '1');
        $("#login").hide();
        $("#loggedin").show();
      }
    }
  });
};

Can you share an example or explanation that would help me figure out how to use Sinon to test this function. Or is the function implemented improperly?

The username and password are passed in to the ajax call post data. The spy and mock examples I've found for testing ajax posts don't usually have that and they use a callback. My callback is internal... the success method.

teaman
  • 469
  • 7
  • 18
  • did u try to mock server response with sinon useFakeXMLHttpRequest? Then u can check if code in success with stubs. Or u can extract success function and just test it without testing jquery method since it's not your code. – erhardos Nov 07 '17 at 23:27
  • Possible duplicate of https://stackoverflow.com/questions/5272698/how-to-fake-jquery-ajax-response – djfdev Nov 07 '17 at 23:57
  • No, not a duplicate as that one is yet another example that tries to replace the direct $.ajax call. That's why I posted this one, in my case I have a wrapper function and not sure how to test it. – teaman Nov 08 '17 at 00:02

0 Answers0