mock模拟ajax,GitHub - mobz/mock-ajax: a framework for mocking ajax requests with jQuery and jsHamcrest...

MockAjax是一个用于JavaScript测试的库,它允许在不需要真实服务器的情况下模拟异步XHR请求。该库特别适用于JsHamcrest、jQuery和PrototypeJS,并支持多种测试框架如jasmine、JsUnitTest等。MockAjax可以让你设置预期的请求和响应,测试服务器依赖代码,处理并发请求,测试错误情况如超时和404错误。它还提供了一种方式来即时响应setTimeout,支持同步和异步AJAX请求。通过定义回调函数,你可以动态地定义响应,增加了测试的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MockAjax

MockAjax is an mock XMLHttpRequest implemetation designed to allow asyncronous

xhr requests to be run inside a synchronous testing framework. It is specifically

designed to run with JsHamcrest and jQuery or PrototypeJS and inside many different unit testing frameworks.

Includes support for jsTestDriver, jasmine, JsUnitTest, jsUnity, QUnit, Rhino, YIUTest and screwunit

So what does it do?

Mock out Ajax requests, so a server is not required to test server dependant code

Allow asyncronous requests to run synchronously, allowing tests to run much faster than normal

Allow you to test multiple simultaneous inflight requests

Allow tricky edge cases to be tested with ease

server timeouts

receiving server responses out of order

404’s

server errors

Allows tests that use setTimeout to run instantly and reliably

also supports asynchronous and synchronous ajax without blocking

Show me

// fetch an article from the server and put it in a div on the page

// set up our expectations (you can think of this as a virtual server)

whenRequest({ url: is("/api/article/1") })

.thenRespond({ type: "html", data: "

Article Title

this is the body

" });

// run the code under test

jQuery.ajax( {

url: "/api/article/1",

success: function(article) {

$("#doc").html(article);

}

} );

// trigger the respond from the server

MockAjax.respond();

// assert that the test ran correctly

assertThat($("#doc > H2").text(), equalTo("Article Title"), "title correctly applied to article heading");

assertThat($("#doc > P").text(), equalTo("this is the body"), "body correctly applied to article paragraph");

How do I use it

First of all, this framework requires JsHamcrest (or something which uses hamcrest compatible matchers), so you need to be using that.

Right after the JsHamcrest.Integration is preformed, add this line

MockAjax.Integration.JsTestDriver().jQuery();

Integration commands can be chained and the following frameworks are supported

testing frameworks

jasmine

JsTestDriver

JsUnitTest

jsUnity

QUnit

Rhino

YUITest

screwunit

development frameworks

jQuery

Prototype

Zepto

I want more

whenRequest

Each parameter to whenRequest takes a hamcrest matcher . All parameters are optional

You can create as many whenRequest / thenRespond pairs as you like

method matches the request method (GET, POST, HEAD etc)

url matches the url component

data matches the request body (usually blank for GET requests, or contains form data)

headers matches the map of request headers (eg Cookie, Referer)

async matches the async flag (either true or false )

username matches the HTTP username

password matches the HTTP password

examples:

whenRequest({ method: anyOf("PUT", "DELETE"), url: matches(/blog\/\d+/), username: is("admin") })

thenRespond

Each parameter passed to thenRespond constitutes some part of the response from the server

status (default = 200) the HTTP status code for the response

data (default = "") the responseText or responseXML that forms the body of the response

type (default = “json”) a short cut for setting the Content-Type header (acceptable values are json, html, text, script, xml, default )

headers additional headers that you want to include in the response.

Note that by default MockAjax provides some basic headers that are required to get the mock working in jQuery, any that are provided override the built in ones.

By default there is one built in response that will be returned if no request matches and that is a 404 – file not found response

examples:

thenRespond({ type: "html", data: "

hello world
" });

thenRespond({ data: '{"this":"is","some":["json","data"]}' });

thenRespond({ status: 500, data: "Fatal error: Call to undefined function: mysql_set_charset() in /pages/includes/comments.php on line 152" });

thenRespond({ status: 401, headers: { "WWW-Authenticate": "Basic realm=\"intranet\"" }, data: "401 - Unauthorized" });

Dynamic Responses

Rather than specifying the responses for each request statically, you can define a callback function which returns an object containing any response parameters. The callback is provided with the original request.

function callback(request, mockXHRObject) { return { [status | data | type | headers ] }; }

examples:

// echo the request method and url back as the response

thenRespond( function( req ) { return { type: "text", data: ( req.method + req.url ) } } );

// modify the body based on the url parameter

thenRespond( function (req) { return { type: "text", data: "hello " + req.url.match(/?name=(\w+)/ ) } } );

// set the last modified header to right now

thenRespond( function (req) { return { headers: { "Last-Modified" : (new Date()).toUTCString() } } } );

MockAjax.respond()

the respond method causes MockAjax to respond with the oldest ajax response in it’s queue. The respond method is not required for synchronous ajax requests.

if there are multiple inflight requests at once, you can cause responses to return out-of-order by passing a non-zero number.

MockAjax.respond(3) causes the fourth queued response to be returned

MockAjax.respondAll()

the respondAll method causes MockAjax to respond to all of the ajax responses in it’s queue, oldest first. The respondAll method is not required for synchronous ajax requests.

MockAjax.timeout()

the timeout method causes any queued calls to setTimeout to be executed. All calls to setTimeout are trapped, so if you have multiple timers you will need to call timeout multiple times to clear them all.

// example testing the timeout feature of some code

// fire off the ajax request

jQuery.ajax( {

url: "/article/12",

timeout: 60000, // one minute (but we don't want wait that long for the test!)

success: this.doSomething,

error: function(x, e) { if(e === "timeout") { $("#doc").text("Error: the request timed out. Perhaps the server died"); } }

} );

// force the timeout

MockAjax.timeout();

// assert that the test ran correctly

assertThat( $("#doc").text(), contains("timed out"), "testing request timeout handling");

资源下载链接为: https://pan.quark.cn/s/9e7ef05254f8 在网页设计中,为图片添加文字是一种常见的需求,用于增强视觉效果或传达更多信息。本文将介绍两种常用的方法:一种是将图片设置为背景并添加文字;另一种是利用<span>标签结合CSS定位来实现。 这种方法通过CSS实现,将图片设置为一个容器(通常是<div>)的背景,然后在容器中添加文字。具体步骤如下: 创建一个包含文字的<div>元素: 使用CSS设置<div>的背景图片,并调整其尺寸以匹配图片大小: 如有需要,可使用background-position属性调整图片位置,确保文字显示在合适位置。这样,文字就会显示在图片之上。 另一种方法是将文字放在<span>标签内,并通过CSS绝对定位将其放置在图片上。步骤如下: 创建一个包含图片和<span>标签的<div>: 设置<div>为相对定位,以便内部元素可以相对于它进行绝对定位: 设置<span>为绝对定位,并通过调整top和left属性来确定文字在图片上的位置: 这种方法的优点是可以精确控制文字的位置,并且可以灵活调整文字的样式,如颜色和字体大小。 两种方法各有优势,可根据实际需求选择。在实际开发中,还可以结合JavaScript或jQuery动态添加文字,实现更复杂的交互效果。通过合理运用HTML和CSS,我们可以在图片上添加文字,创造出更具吸引力的视觉效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值