关于前后端分离开发的方法,jQuery的Mockjax:Ajax请求模拟

来源:互联网 发布:古装网络剧自制剧男同 编辑:程序博客网 时间:2024/06/07 23:57

大多数后端开发人员都熟悉的概念,模拟的对象或方法存根进行单元测试。Mockjax给前端开发人员定义的,以及这些请求应如何响应Ajax请求的能力。这些例子可以非常简单或相当复杂的,占整个请求-响应工作流程。

概述:第一个例子

我们的第一个例子将是一个发财的应用程序与REST端点存在一个简单的REST服务/restful/fortune返回以下JSON消息:

{    "status": "success",    "fortune" : "Are you a turtle?"}

拉到我们的页面,我们可以使用下面的HTML和jQuery代码:

<!DOCTYPE html><html>  <head>    <title>Fortune App</title>    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>  </head><body>  <div id="fortune"></div></body></html>
$.getJSON("/restful/fortune", function(response) {  if ( response.status == "success") {    $("#fortune").html( "Your fortune is: " + response.fortune );  } else {    $("#fortune").html( "Things do not look good, no fortune was told" );  }});

此时,如果我们运行这段代码,它会失败,因为REST服务还有待落实。这就是Mockjax插件的好处开始获得回报。使用Mockjax的第一步是只需添加一个标签包括插件:

<head>  ...  <script src="vendor/jquery.mockjax.js"></script></head>

一旦你引用了,你就可以开始拦截Ajax请求和嘲讽的回应。因此,让我们通过包括下面的代码模拟出的服务:

$.mockjax({  url: "/restful/fortune",  responseText: {    status: "success",    fortune: "Are you a mock turtle?"  }});

定义一个JSON字符串内联需要一个JSON.stringify()可用的方法。对于某些浏览器,你可能需要包括 json2.js,它包含了在lib文件夹中。但是,你也可以简单地在提供您的JSON已经字符串化版本responseText 属性。

如果你打算模拟XML响应,您可能还包括 jquery.xmldom.js,它也可以在中找到的lib文件夹中。

详细的请求和响应定义

定义一个请求匹配

你需要模拟的请求时做的第一件事是定义URL终点拦截和模拟。正如我们上面这个例子可以是一个简单的字符串:

$.mockjax({  url: "/url/to/rest-service"});

或含有一个*作为通配符:

$.mockjax({  // Matches /data/quote, /data/tweet etc.  url: "/data/*"});

或完整的正则表达式:

$.mockjax({  // Matches /data/quote, /data/tweet but not /data/quotes  url: /^\/data\/(quote|tweet)$/i});

您也可以匹配除了URL数据选项:

$.mockjax({  url:  "/rest",  data: { action: "foo" }});

数据选项可以是定制匹配函数返回truefalse 数据是否预期与否:

$.mockjax([  url: "/rest",  data: function( data ) {    return deepEqual( data, expected );  }]);

数据功能是断言一个推荐的地方。返回true并让所选择的测试框架做休息:

$.mockjax([  url: "/rest",  data: function ( json ) {    assert.deepEqual( JSON.parse(json), expected ); // QUnit example.    return true;  }]);

要捕获的URL参数,使用捕捉正则表达式的URL和一个urlParams阵列,以指示,序数型标尺,将捕获的paramters的名称:

$.mockjax({  // matches /author/{any number here}/isbn/{any number with dashes here}  // for example: "/author/1234/isbn/1234-5678-9012-0"  url: /^\/author\/([\d]+)\/isbn\/([\d\-]+)$/,  // names of matching params  urlParams: ["authorID", "isbnNumber"],  response: function (settings) {    var authorID = settings.urlParams.authorID;    var isbnNumber = settings.urlParams.isbnNumber;    // etc...  }});

定义多个请求

自2.2版本,它允许定义一次多个请求。 $.mockjax([...])返回处理程序“索引的数组。有可能通过索引复位处理程序。更多在拆卸Mockjax处理程序。

var handlers = $.mockjax([  {url: '/rest', responseText: 'one'},  {url: '/rest', responseText: 'two'}]);$.mockjax.clear(handlers[0]);

定义响应

第二步骤是定义响应的类型和内容。您将处理的两个主要特性是不是responseText还是 responseXML。这些属性镜像本地XMLHttpRequest 被实时响应时设定对象属性。有指定的响应三种不同的模式:内联,代理和回调。

内联响应

一个简单的文本的反应是:

$.mockjax({  url: "/restful/api",  responseText: "A text response from the server"});

一个简单的JSON的反应是:

$.mockjax({  url: "/restful/api",  // You may need to include the [json2.js](https://raw.github.com/douglascrockford/JSON-js/master/json2.js) library for older browsers  responseText: { "foo": "bar" }});

另外请注意,JSON响应实际上只是一个文本反应,jQuery将作为JSON解析你(并返回一个JSON对象到successcomplete回调)。

一个简单的XML响应将是:

$.mockjax({  url: "/restful/api",  // Need to include the xmlDOM plugin to have this translated into a DOM object  responseXML: "<document><quote>Hello world!</quote></document>"});

正如你所看到的,如果你大量数据难以处理。所以这给我们带来了下一个模式:Proxy。

Proxy

在下面这个例子中,Mockjax插件将拦截的请求 /restful/api,并将其重定向到/mocks/data.json

$.mockjax({  url: "/restful/api",  proxy: "/mocks/data.json"});

/mocks/data.json文件可以有你想要的任何有效的JSON的内容,并允许您维护它自己的文件可维护性的模拟数据。

注意:如果你与丙氧基测试代码,最好是运行测试实际的Web服务器。简单地载入test/index.html从文件系统可能会导致无法正确加载代理文件。我们建议使用类似的http-serverNPM模块。

Callback

在最后的反应模式,我们可以定义上的回调函数 response属性和有它设置responseTextresponseXML根据需要:

$.mockjax({  url: "/restful/api",  response: function(settings) {    // Investigate the `settings` to determine the response...    this.responseText = "Hello world!";  }});

这个回调的缺省版本是同步的。如果您提供两个参数的回调函数,你可以使用异步代码设置的动态响应。

$.mockjax({  url: '/restful/api',  response: function(settings, done) {    var self = this;    someAsyncMethod(function(data){      self.responseText = data;      done();    });  }});

请注意,回调给提供给设置$.mockjax({...}) 方法合并的jQuery或您的应用程序定义的任何Ajax的设置。这可以让你彻底调查设置响应体(或头)的请求之前。

先进的模拟技术

以上,我们已经看到了一系列与Mockjax基本模拟的技术,现在将解压所载的某些插件的附加功能。

模拟响应时间和等待时间

模拟的网络和服务器延迟的模拟,只需添加一个简单responseTime属性的模拟定义:

$.mockjax({  url: "/restful/api",  // Simulate a network latency of 750ms  responseTime: 750,  responseText: "A text response from the server"});

您也可以使用间隔responseTime随机化延迟:

$.mockjax({  url: "/restful/api",  // Use a random value between 250ms and 750ms  responseTime: [250, 750],  responseText: "A text response from the server"});

模拟HTTP响应以下状态

它也可以通过简单地增加一个模拟超过200(默认Mockjax)其他响应状态status财产。

$.mockjax({  url: "/restful/api",  // Server 500 error occurred  status: 500,  responseText: "A text response from the server"});

就像如果服务器已经返回的错误,这些错误强制状态代码将被处理:在error回调将使用适当的参数得到执行。

设定内容类型

您可以设置内容类型与模拟响应相关联,在下面的例子中,我们设置一个JSON内容类型。

$.mockjax({  url: "/restful/api",  contentType: "application/json",  responseText: {    hello: "World!"  }});

设置附加HTTP响应头

响应头可以通过设置在头部的关键提供附加HTTP对象字面值:

$.mockjax({  url: "/restful/api",  contentType: "application/json",  responseText: {    hello: "World!"  },  headers: {    etag: "xyz123"  }});

动态生成模拟的定义

在某些情况下,你的所有REST调用的是基于一个URL模式。Mockjax已经为你指定被交到一个回调函数的能力$.ajax要求设置。然后,回调函数既可以返回false允许请求被处理本身,或者返回一个对象字面设定相关参数Mockjax。下面是重写所有的Ajax请求代理到静态嘲笑一个例子:

$.mockjax(function(settings) {  // settings.url might be: "/restful/<service>" such as "/restful/user"  var service = settings.url.match(/\/restful\/(.*)$/);  if ( service ) {    return {      proxy: "/mocks/" + service[1] + ".json"    };  }  // If you get here, there was no url match  return;});

访问请求头

在某些情况下,你可能需要访问请求头,以确定匹配或响应机构。要做到这一点,你需要指定一个递给一个回调函数$.ajax请求设置:

$.mockjax(function( requestSettings ) {  // Here is our manual URL matching...  if ( requestSettings.url === "/restful/user" ) {    // We have a match, so we return a response callback...    return {      response: function( origSettings ) {        // now we check the request headers, which may be set directly        // on the xhr object through an ajaxSetup() call or otherwise:        if ( requestSettings.headers["Authentication"] === "some-token" ) {          this.responseText = { user: { id: 13 } };        } else {          this.status = 403;          this.responseText = "You are not authorized";        }      }    };  }  // If you get here, there was no url match  return;});

服务器超时强制模拟

由于方式Mockjax开始实施,它利用jQuery的内部超时处理的请求。但是,如果你想强制超时的请求,你可以通过设置这样做的isTimeout 属性设置为true:

$.mockjax({  url: '/restful/api',  responseTime: 1000,  isTimeout: true});
更多关于jquery-mockjax的一些功能和api可以访问他的官网查看,网址https://github.com/jakerella/jquery-mockjax#jquery-mockjax-ajax-request-mocking

原创粉丝点击