Created
August 28, 2015 20:26
-
-
Save duongphuhiep/f4c807309a25906fc1c1 to your computer and use it in GitHub Desktop.
Use sinon.js to create a fake RESTful Server, and simulate ajax response for some specifics XMLHttpRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sinon = require("sinon"); | |
var utils = require('../lib/utils'); | |
var xhr = sinon.useFakeXMLHttpRequest(); //in fact xhr === sinon.FakeXMLHttpRequest | |
xhr.useFilters = true; | |
xhr.addFilter(function(method, url, async, username, password) { | |
console.log('check filter on', method, url, async, username, password); | |
var parsedUrl= utils.parseUri(url); | |
//mock all the request which filename ends with .php | |
var patt = /.+\.php$/; | |
if (patt.test(parsedUrl.file)) { | |
return false; //return false to mock the request and return fake the result | |
} | |
return true; //return true to use the native XMLHttpRequest | |
}); | |
var server = sinon.fakeServer.create({autoRespond: true, autoRespondAfter: 1000}); | |
//server.respondWith(/\/post\.php\?id=(\d+)/, function (request, id) { | |
// console.log("response with", request, id); | |
// request.respond(200, {"Content-Type": "text/plain"}, "Here the content "+id); | |
//}); | |
server.respondWith(function(request){ | |
console.log("response generic", request); | |
var parsedUrl= utils.parseUri(request.url); | |
var responseContent = { | |
"directory": parsedUrl.directory, | |
"file": parsedUrl.file, | |
"page": parsedUrl.queryKey.page, | |
"lang": parsedUrl.queryKey.lang | |
}; | |
request.respond(200, {"Content-Type": "application/json"}, JSON.stringify(responseContent)); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Sinon various test</title> | |
</head> | |
<body> | |
<h1>Real Response</h1> | |
<pre id="real"></pre> | |
<h1>Fake Response</h1> | |
<pre id="fake"></pre> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/string.js/3.3.1/string.min.js"></script> | |
<script src="../dist/fake-backend.js"></script> | |
<script> | |
function load(src, containerId) { | |
var oReq = new XMLHttpRequest(); | |
oReq.onload = function(e) { | |
console.log("onLoad", oReq); | |
}; | |
oReq.onreadystatechange = function (e) { | |
//console.log(oReq.method); | |
if (oReq.readyState === 4) { | |
if (oReq.status === 200) { | |
var mimeType = oReq.getResponseHeader("content-type"); | |
var content = oReq.responseText; | |
if (S(mimeType).startsWith("text")) { | |
$("#"+containerId).text(content); | |
} | |
else { | |
var resu = JSON.parse(content); //the json response is parsed to a javascript object | |
$("#" + containerId).text(JSON.stringify(resu, null, 2)); //display this object in a pretty json format | |
} | |
} else { | |
$("#"+containerId).text("ERROR " | |
+ oReq.status | |
+ " (" + oReq.statusText + "): " | |
+ oReq.responseText | |
+" \n"+JSON.stringify(oReq, null, 2)); //pretty json print | |
} | |
} | |
}; | |
oReq.open('get', src); | |
oReq.send(); | |
} | |
$(function() { | |
//Use real XMLHttpRequest | |
load('blogpage.json', 'real'); | |
//load('backend/blog.php?page=1&lang=fr', 'fake'); | |
load('backend/post.php?id=100&lang=fr', 'fake'); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by hiep on 28/08/2015. | |
*/ | |
/** | |
* Parse RFC 3986 compliant URIs. | |
* Based on parseUri by Steven Levithan <stevenlevithan.com> | |
* See http://blog.stevenlevithan.com/archives/parseuri | |
* | |
* Example: parse "backend/blog.php?page=1&lang=fr" to | |
* { | |
anchor: "", | |
authority: "", | |
directory: "backend/", | |
file: "blog.php", | |
host: "", | |
password: "", | |
path: "backend/blog.php", | |
port: "", | |
protocol: "", | |
query: "page=1&lang=fr", | |
queryKey: { lang: "fr", page: "1" }, | |
relative: "backend/blog.php?page=1&lang=fr", | |
source: "backend/blog.php?page=1&lang=fr", | |
user: "", | |
userInfo: "" | |
} | |
*/ | |
module.exports.parseUri = function(str) { | |
var pattern = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/; | |
var key = ["source", "protocol", "authority", "userInfo", "user", | |
"password", "host", "port", "relative", "path", | |
"directory", "file", "query", "anchor"]; | |
var querypattern = /(?:^|&)([^&=]*)=?([^&]*)/g; | |
var match = pattern.exec(str); | |
var uri = {}; | |
var i = 14; | |
while (i--) { | |
uri[key[i]] = match[i] || ""; | |
} | |
uri.queryKey = {}; | |
uri[key[12]].replace(querypattern, function ($0, $1, $2) { | |
if ($1) { | |
uri.queryKey[$1] = $2; | |
} | |
}); | |
return uri; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment