Fixtures simulate AJAX responses. Instead of making a request to a server, fixtures simulate the response with a file or function. They are a great technique when you want to develop JavaScript independently of the backend.
There are two common ways of using fixtures. The first is to
map Ajax requests to another file or function. The following
intercepts requests to /tasks.json and directs them
to fixtures/tasks.json:
$.fixture("/tasks.json","fixtures/tasks.json");
You can also add a fixture option directly to $.ajax like:
$.ajax({url: "/tasks.json",
dataType: "json",
type: "get",
fixture: "fixtures/tasks.json",
success: myCallback
});
The first technique keeps fixture logic out of your Ajax requests. However, if your service urls are changing a lot the second technique means you only have to change the service url in one spot.
There are 2 types of fixtures: - 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 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");
$.ajax({type:"get",
url: "tasks/1",
fixture: "fixtures/task1.json"})
// looks in fixtures/tasks1.json relative to jmvc root
// this assumes you are using steal
$.fixture("tasks/1", "//fixtures/task1.json");
$.ajax({type:"get",
url: "tasks/1",
fixture: "//fixtures/task1.json"})`
Dynamic Fixtures are functions that return the arguments the $.ajax callbacks
(beforeSend, success, complete,
error) expect.
For example, the "success" of a json request is called with
[data, textStatus, XMLHttpRequest].
There are 2 ways to lookup dynamic fixtures. They can provided:
//just use a function as the fixture property
$.ajax({
type: "get",
url: "tasks",
data: {id: 5},
dataType: "json",
fixture: function( settings, callbackType ) {
var xhr = {responseText: "{id:"+settings.data.id+"}"}
switch(callbackType){
case "success":
return [{id: settings.data.id},"success",xhr]
case "complete":
return [xhr,"success"]
}
}
})
Or found by name on $.fixture:
// add your function on $.fixture
// We use -FUNC by convention
$.fixture["-myGet"] = function(settings, cbType){...}
// reference it
$.ajax({
type:"get",
url: "tasks/1",
dataType: "json",
fixture: "-myGet"})
Dynamic fixture functions are called with:
$.ajax()
"beforeSend", "success", "complete",
"error"and should return an array of arguments for the callback.
The fixture plugin comes with a few ready-made dynamic fixtures and fixture helpers:
new $.fixture(settings) -> String
{Object}
{String}
the url that will be used for the fixture