提问人:JohnK 提问时间:3/11/2020 最后编辑:JohnK 更新时间:3/14/2020 访问量:777
如何存根其响应取决于传递的数据的 AJAX 请求?
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 请求是以任意顺序发出的。此外,传递的数据只是一个参数。
答:
0赞
dajnz
3/11/2020
#1
如果您使用的是基于 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' },
];
});
评论
0赞
JohnK
3/11/2020
感谢您的回复,@dajnz。您能否澄清一下如何使用 NodeJS 库进行客户端测试?
0赞
JohnK
3/12/2020
#2
在线文档非常稀疏,但我找到了方法定义(Jasmine v3.4.0),它回答了我的问题:
this.stubRequest = function(url, data, method) {
var stub = new $ajax.RequestStub(url, data, method);
stubTracker.addStub(stub);
return stub;
};
参数是一个对象,键和值是 URL 参数和值。data
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
});
评论