[jQuery] $.fixture介紹:模擬ajax Request Callback

- - posted in jquery | Comments

$.fixture可以攔截ajax請求並且模擬可能的回應,回應可以從一個檔案(json格式)或某個callback函式。 這對你在開發js而不想依賴後端回應的時候很有用。


Fixtrue有兩種常見的使用方式,第一個是使用靜態檔案回應ajax請求。 下面這個敘述會攔截對tasks.json的請求,將它導向fixtures/tasks.json這個檔案的內容:



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

我們將fixture分為兩種型態: * 靜態fixture – 用檔案內容回應。 * 動態fixture – 用函式產生的資料回應。




// 使用相對位置
$.fixture("tasks/1", "fixtures/task1.json");

// 使用絕對位置
$.fixture("tasks/1", "//fixtures/task1.json");




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


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


  • 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:

    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 to false:

$.fixture.on = false;


$.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.’