![](/img/trans.png)
[英]How can I synchronize javascript code that depends on the response of multiple ajax requests?
[英]How do I stub AJAX requests whose response depends on data passed?
我正在尝试使用 Jasmine 进行单元测试。 我需要模拟对同一个 URL 的两个 AJAX GET 请求,但其响应取决于请求中传递的数据。 到目前为止,我一直无法找到有关如何使响应依赖于除 URL 之外的任何内容的任何信息。
我一直在尝试使用stubRequest
方法:
jasmine.Ajax.stubRequest('MY_URL.json')
.andReturn({
"status": 200,
"contentType": 'application/json',
"responseText": rawData
});
我还应该提到 AJAX 请求是以任意顺序发出的。 此外,传递的数据只是一个参数。
如果您使用的是基于 Nodejs 的环境,那么这个库将帮助您。
此示例描述了如何使用库根据请求数据返回不同的响应:
const myRequestStub = nock('http://my-domain.tld')
.post('/some/request/path')
.reply(201, (uri, requestBody) => {
// Here you can do what you want and return response depending on the request
return [
// Response HTTP code
201,
// Response
'this is my custom response body',
// optional headers
{ header: 'value' },
];
});
在线文档非常稀疏,但我找到了方法定义(Jasmine v3.4.0),它回答了我的问题:
this.stubRequest = function(url, data, method) {
var stub = new $ajax.RequestStub(url, data, method);
stubTracker.addStub(stub);
return stub;
};
data
参数是一个对象,其键和值是 URL 参数和值。
jasmine.Ajax.stubRequest('MY_URL.json', {param1: "value1"}, "GET")
.andReturn({
"status": 200,
"contentType": 'application/json',
"responseText": rawData
});
或者是这样,我想。 实际上,虽然这可能适用于 POST,但对于我尝试执行的 GET 请求,事实证明您必须直接将参数添加到 URL。 所以对于OP中的请求,
jasmine.Ajax.stubRequest('MY_URL.json?param1=value1')
.andReturn({
"status": 200,
"contentType": 'application/json',
"responseText": rawData
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.