Mocking AJAX responses by using a Media type string

When you want to test how your code handles API requests, or any AJAX requests – you will most likely find yourself in a situation where you don’t actually test the code responsible for the request, but just a “hardcoded” response that you provide in the code.

it might look like that:

if (testEnv) {
    doSomethingWithTheResponse({
        foo: 'bar'
    });
} else {
    $.get('/api/get_response_url').success(function(res) {
        doSomethingWithTheResponse(res)});
    }
}

in most cases it will do just fine – but what if there is a complex and crucial functionality within the .success callback?

the answer would be: Mock AJAX response while preserving the actual request code block. like this:

var url = '/api/get_response_url';

if (testEnv) {
    url = 'data:application/json,{"foo":"bar"}';
}

$.get(url).success(function(res) {
    doSomethingWithTheResponse(res);
});

in the above example we are setting the request url to be a media type string, which consists of:

  • top level type: data
  • type: application
  • subtype: json
  • parameters: {“foo”: “bar”}

you can read more about media types and their syntax here.

The request we do now returns what it has in the media type parameter – which is a completely valid, actual AJAX request with our mock response.

Leave a Reply

Your email address will not be published. Required fields are marked *