title: mocking jquery $.ajax with jest
body: <p>Using jest how can I test a function that makes an ajax request in my jQuery app and mock its response? My app is not compiled in nodejs and runs straight in a browser. The example on the jest site <a href="https://github.com/facebook/jest/tree/master/examples/jquery" rel="noreferrer">https://github.com/facebook/jest/tree/master/examples/jquery</a> assumes ajax function is a separate module and the whole app gets compiled with something like webpack. Here is my app:</p>
  
  <pre><code>(function(root) {
      "use strict";
      // if environment is node then import jquery.
      var $ = (typeof module === "object" &amp;&amp; module.exports) ? require('jquery') : jQuery;
  
  
      function displayUser() {
  
          var fetchCurrentUser = function (url) {
              var xhr = $.get(url);
              $.when(xhr)
                  .done(function(data) {
                      greet(data);
                  })
                  .fail(function(jqXHR, textStatus, errorThrown) {
                      console.log(errorThrown);
                  });
           };
  
          var greet = function(data) {
              $('#greet').text('Hello ' + data.name);
          }
  
          fetchCurrentUser('/my/api');
  
          return {
              fetchCurrentUser: fetchCurrentUser,
              greet: greet
          };
      }
  
      // Added this conditional so I can test in jest
      if (typeof module === "object" &amp;&amp; module.exports) {
          // Node
          module.exports = displayUser();
      } else {
          // Browser (root is window)
          root.displayUser = displayUser();
      }
  })(this);
  </code></pre>