jQuery.fixture  function     

plugin: jquery/dom/fixture
download: jQuery.fixture
test: qunit.html
Source

$.fixture intercepts a AJAX request and simulates the response with a file or function. They are a great technique when you want to develop JavaScript independently of the backend.

Types of Fixtures

There are two common ways of using fixtures. The first is to map Ajax requests to another file. The following intercepts requests to /tasks.json and directs them to fixtures/tasks.json:

$.fixture("/tasks.json","fixtures/tasks.json");

The other common option is to generate the Ajax response with a function. The following intercepts updating tasks at /tasks/ID.json and responds with updated data:

$.fixture("PUT /tasks/{id}.json", function(original, settings, headers){
   return { updatedAt : new Date().getTime() }
})

We categorize fixtures into the following types:

  • Static - the response is in a file.
  • Dynamic - the response is generated by a function.

There are different ways to lookup static and dynamic fixtures.

Static Fixtures

Static fixtures use an alternate url as the response of the Ajax request.

// looks in fixtures/tasks1.json relative to page
$.fixture("tasks/1", "fixtures/task1.json");

$.fixture("tasks/1", "//fixtures/task1.json");

Dynamic Fixtures

Dynamic Fixtures are functions that get the details of the Ajax request and return the result of the mocked service request from your server.

For example, the following returns a successful response with JSON data from the server:

$.fixture("/foobar.json", function(orig, settings, headers){
  return [200, "success", {json: {foo: "bar" } }, {} ]
})

The fixture function has the following signature:

function( originalOptions, options, headers ) {
  return [ status, statusText, responses, responseHeaders ]
}

where the fixture function is called with:

  • originalOptions - are the options provided to the ajax method, unmodified, and thus, without defaults from ajaxSettings
  • options - are the request options
  • headers - a map of key/value request headers

and the fixture function returns an array as arguments for ajaxTransport's completeCallback with:

  • status - is the HTTP status code of the response.
  • statusText - the status text of the response
  • responses - a map of dataType/value that contains the responses for each data format supported
  • headers - response headers

However, $.fixture handles the common case where you want a successful response with JSON data. The previous can be written like:

$.fixture("/foobar.json", function(orig, settings, headers){
  return {foo: "bar" };
})

If you want to return an array of data, wrap your array in another array:

$.fixture("/tasks.json", function(orig, settings, headers){
  return [ [ "first","second","third"] ];
})

$.fixture works closesly with jQuery's ajaxTransport system. Understanding it is the key to creating advanced fixtures.

Templated Urls

Often, you want a dynamic fixture to handle urls for multiple resources (for example a REST url scheme). $.fixture's templated urls allow you to match urls with a wildcard.

The following example simulates services that get and update 100 todos.

// create todos
var todos = {};
for(var i = 0; i < 100; i++) {
  todos[i] = {
    id: i,
    name: "Todo "+i
  }
}
$.fixture("GET /todos/{id}", function(orig){
  // return the JSON data
  // notice that id is pulled from the url and added to data
  return todos[orig.data.id]
})
$.fixture("PUT /todos/{id}", function(orig){
  // update the todo's data
  $.extend( todos[orig.data.id], orig.data );

  // return data
  return {};
})

Notice that data found in templated urls (ex: {id}) is added to the original data object.

Simulating Errors

The following simulates an unauthorized request to /foo.

$.fixture("/foo", function(){
    return [401,"{type: 'unauthorized'}"]
   });

This could be received by the following Ajax request:

$.ajax({
  url: '/foo',
  error : function(jqXhr, status, statusText){
    // status === 'error'
    // statusText === "{type: 'unauthorized'}"
  }
})

Turning off Fixtures

You can remove a fixture by passing null for the fixture option:

// add a fixture
$.fixture("GET todos.json","//fixtures/todos.json");

// remove the fixture
$.fixture("GET todos.json", null)

You can also set [jQuery.fixture.on $.fixture.on] to false:

$.fixture.on = false;

Make

$.fixture.make makes a CRUD service layer that handles sorting, grouping, filtering and more.

Testing Performance

Dynamic fixtures are awesome for performance testing. Want to see what 10000 files does to your app's performance? Make a fixture that returns 10000 items.

What to see what the app feels like when a request takes 5 seconds to return? Set [jQuery.fixture.delay] to 5000.

Demo

HTML

Source

API

$.fixture(settings, fixture) -> undefined
{Object|String}

Configures the AJAX requests the fixture should intercept. If an object is passed, the object's properties and values are matched against the settings passed to $.ajax.

If a string is passed, it can be used to match the url and type. Urls can be templated, using {NAME} as wildcards.

{Function|String}

The response to use for the AJAX request. If a string url is passed, the ajax request is redirected to the url. If a function is provided, it looks like:

fixture( originalSettings, settings, headers    )

where:

  • originalSettings - the orignal settings passed to $.ajax
  • settings - the settings after all filters have run
  • headers - request headers

If null is passed, and there is a fixture at settings, that fixture will be removed, allowing the AJAX request to behave normally.

{undefined}
� Jupiter Consulting - JavaScriptMVC Training and Support