Skip to content

Instantly share code, notes, and snippets.

@duongphuhiep
Last active August 27, 2015 21:32
Show Gist options
  • Save duongphuhiep/b36a7fffa3fec7d955ac to your computer and use it in GitHub Desktop.
Save duongphuhiep/b36a7fffa3fec7d955ac to your computer and use it in GitHub Desktop.
Simulate responses from external ajax RESTful services by mocking XMLHttpRequest. http://stackoverflow.com/questions/32254959/test-front-end-application-without-back-end
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Try MockHttpRequest</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!--you must to download this script to your local and replace it here-->
<script src="https://raw.githubusercontent.com/philikon/MockHttpRequest/master/lib/mock.js"></script>
</head>
<body>
<h1>Real Response</h1>
<pre id="real"></pre>
<h1>Fake Response</h1>
<pre id="fake"></pre>
<script>
function load(src, containerId) {
var oReq = new XMLHttpRequest();
oReq.onload = function(e) {
console.log(oReq);
};
oReq.onreadystatechange = function (e) {
if (oReq.readyState === 4) {
if (oReq.status === 200) {
var resu = JSON.parse(oReq.responseText); //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('backend/blog.php?page=1&lang=fr', 'real');
//Use mock XMLHttpRequest
var mockServer = new MockHttpServer();
mockServer.handle = function(request) {
request.setResponseHeader("Content-Type", "application/json");
var responseContent = {
"url":request.url,
"directory": request.urlParts.directory,
"file": request.urlParts.file,
"page": request.urlParts.queryKey.page,
"lang": request.urlParts.queryKey.lang
};
//response immediately
//request.receive(200, JSON.stringify(responseContent));
//or simulate connection latency: wait 2sec before response
//window.setTimeout(function(){
// request.receive(200, JSON.stringify(responseContent));
//}, 2000);
//or generate response from other json file on localhost
var oReq = new OriginalHttpRequest(); //this is the real XMLHttpResponse
oReq.onload = function(e) {
responseContent["JsonFromLocalhostFile"] = JSON.parse(oReq.responseText);
request.receive(200, JSON.stringify(responseContent));
};
oReq.open('get', "blogpage2.json"); //grab a json file from localhost to use as response to this request
oReq.send();
};
mockServer.start();
load('backend/blog.php?page=1&lang=fr', 'fake');
mockServer.stop();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment