How to fake jquery.ajax() response?

前端 未结 6 500
孤独总比滥情好
孤独总比滥情好 2020-12-07 20:56

I am writing some QUnit tests for a JavaScript that makes AJAX calls.

For isolation I overwrite $.ajax to write the parameter array of an AJAX call to a

6条回答
  •  温柔的废话
    2020-12-07 21:11

    Mock $.ajax as needed without disturbing jQuery

    The answers here are good but had a specific need to build out a fake response to a single API call while leaving all other API calls the same until the backend service was built out so I can continue building stuff on the UI.

    The API object uses $.ajax under the hood so you can call an API method like so:

    api.products({ price: { $lt: 150, tags: ['nike', 'shoes'] } })
    .done(function(json) {
      // do something with the data
    })
    .error(function(err) {
      // handle error
    });
    

    This method does the trick:

    function mockAjax(options) {
      var that = {
        done: function done(callback) {
          if (options.success)
            setTimeout(callback, options.timeout, options.response);
          return that;
        },
        error: function error(callback) {
          if (!options.success)
            setTimeout(callback, options.timeout, options.response);
          return that;
        }
      };
      return that;
    }
    

    Then override a single api call without touching $.ajax:

    api.products = function() {
      return mockAjax({
        success: true,
        timeout: 500,
        response: {
          results: [
            { upc: '123123', name: 'Jordans' },
            { upc: '4345345', name: 'Wind Walkers' }
          ]
        }
      });
    };
    

    https://jsfiddle.net/Lsf3ezaz/2/

提交回复
热议问题