[英]Test front-end application without back-end
My web application uses XMLHttpRequest
to load JSON data returned by a backend server running PHP. 我的Web应用程序使用
XMLHttpRequest
来加载运行PHP的后端服务器返回的JSON数据。 It then renders the result in the browser using a client-side Javascript templating library. 然后,它使用客户端Javascript模板库在浏览器中呈现结果。
function load(src) {
var oReq = new XMLHttpRequest();
oReq.onload = function () {
_this.data = JSON.parse(oReq.responseText);
_this.render(_this.data);
};
oReq.open('get', src, opts.async || true);
oReq.send();
}
load('article.php?page=1&lang=en');
load('userprofile.php?userid=1548&lang=en');
The real backend API article.php
is not ready. 真正的后端API
article.php
尚未准备好。 I want to simulate/mock the response of article.php?page=1&lang=en
in order to make an end to end test or to demonstrate the application . 我想模拟/模拟
article.php?page=1&lang=en
的响应, 以便进行端到端测试或演示应用程序 。
How can I change the behaviour of XMLHttpRequest (or mock it) so that it won't open a HTTP connection , but returns pre-configured data according to each request? 如何更改XMLHttpRequest的行为(或对其进行模拟), 使其不会打开HTTP连接 ,而是根据每个请求返回预配置的数据? The mock should simulate a slow connection (delay 1 sec before returning the response) and also support timeout (as the normal XMLHttpRequest).
该模拟应模拟慢速连接(在返回响应之前延迟1秒),并且还应支持超时(与常规XMLHttpRequest一样)。
UPDATE: sinon.js is the right answer 更新: sinon.js是正确的答案
Here an example to show how we can fake a RESTful server which is capable of respond to some specific ajax requests of application (other requests will call the real service) 这是一个示例,展示了我们如何伪造一个RESTful服务器,该服务器能够响应应用程序的某些特定ajax请求(其他请求将调用真实服务)
https://gist.github.com/duongphuhiep/f4c807309a25906fc1c1 https://gist.github.com/duongphuhiep/f4c807309a25906fc1c1
ok, I think this is the answer 好吧,我认为这就是答案
https://github.com/philikon/MockHttpRequest https://github.com/philikon/MockHttpRequest
This library replace the XMLHttpRequest with a mock object. 该库将XMLHttpRequest替换为模拟对象。 So I won't need to refactor or change the existing codes.
因此,我不需要重构或更改现有代码。
In this example: I faked the response coming from backend/blog.php?page=1&lang=fr
在此示例中:我伪造了来自
backend/blog.php?page=1&lang=fr
的响应
https://gist.github.com/duongphuhiep/b36a7fffa3fec7d955ac https://gist.github.com/duongphuhiep/b36a7fffa3fec7d955ac
However, I did not successfully simulate the timeout due to network latency. 但是,由于网络延迟,我没有成功模拟超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.