$.fixture可以攔截ajax請求並且模擬可能的回應,回應可以從一個檔案(json格式)或某個callback函式。 這對你在開發js而不想依賴後端回應的時候很有用。
Fixture的型態
Fixtrue有兩種常見的使用方式,第一個是使用靜態檔案回應ajax請求。
下面這個敘述會攔截對tasks.json
的請求,將它導向fixtures/tasks.json
這個檔案的內容:
$.fixture("/tasks.json","fixtures/tasks.json");
另一個選擇是使用函式動態產生回應資料。下面的敘述攔截對tasks/ID.json
的更新請求,並且回應被更新的資料(事實上沒有更新到伺服端):
$.fixture("PUT /tasks/{id}.json", function(original, settings, headers){
return { updatedAt : new Date().getTime() }
})
我們將fixture分為兩種型態: * 靜態fixture – 用檔案內容回應。 * 動態fixture – 用函式產生的資料回應。
這兩種不同型態各有一些方法去使用它們。
靜態Fixture
靜態fixture使用一個替代URL來回應ajax請求,如下:
// 使用相對位置
$.fixture("tasks/1", "fixtures/task1.json");
// 使用絕對位置
$.fixture("tasks/1", "//fixtures/task1.json");
動態Fixtures
動態fixture實際上就是一個函式。它可以拿到你對ajax請求給予的參數並且回給你假的回應。
例如,下面會回應一個成功的請求,資料則是JSON格式。
$.fixture("/foobar.json", function(orig, settings, headers){
return [200, "success", {json: {foo: "bar" } }, {} ]
})
fixture函數的signature如下
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:
$.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
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.’