title: How to write unit test to embeded ajax requests?
body: <p>I have the handleDownload method which starts a file download. The function posts to the backend, which gives back a response, based on that a new request posts to the server where the files are. I saw that I can use <a href="https://github.com/appendto/jquery-mockjax" rel="nofollow">mockjax</a> to mock the requests, but how to handle the different paths like success, error, etc. How should I know which response triggers which path (success,error, complete, ...). What would be a great startegy to test the handleDownload function, and how? For mocking I use <a href="http://sinonjs.org/" rel="nofollow">Sinon.js</a> I don't have a really deep understanding yet. I should also check either the handleDownloadFinal function is called.</p>
  
  <pre><code>handleDownload: function(data, url) {
  $.ajax({
      type: "POST",
      url: url,
      data: {},
      success: function(response) {
          if (response.success) {
              var start_token = response.token;
              $.ajax({
                  type: start_token.method,
                  url: start_token.url,
                  beforeSend: function(xhr) {
                      xhr.setRequestHeader('Authorization', start_token.header);
                  },
                  success: function(start_response) {
                      handleDownloadFinal(start_response.status_token);
                  },
                  error: function(start_response) {
                      $.ajax({
                          type: "POST",
                          url: url + 'proxy/',
                          success: function(fallback_response) {
                              if (fallback_response.success) {
                                  handleDownloadFinal(fallback_response.status_token, true, fallback_response.job_uuid);
                              } else {
                                  errorDownload(response.error);
                              }
                          },
                          error: function(fallback_response) {
                              // Now this is some real error                                    
                              generalErrorDownload();
                          },
                          dataType: 'json'
                      });
                  },
                  dataType: 'json',
                  xhrFields: {
                      withCredentials: true
                  }
              });
          } else {
              errorDownload(response.error);
          }
      },
      error: function(response) {
          generalErrorDownload();
      },
      complete: function() {
      },
      dataType: "json"
  });
  
  }
  </code></pre>