我正在使用TestCafe Request Mock功能来模拟API响应,如下图所示。
export const deleteDocMock = (status = 200) =>
RequestMock()
.onRequestTo({
url: /\/api\/my-api\/.*/,
method: 'DELETE',
})
.respond({some response}, status, {
'access-control-allow-credentials': 'true',
'access-control-allow-methods': 'GET, POST, PUT, OPTIONS',
});
我可以根据URL和Method类型来过滤请求,但不能根据请求主体来过滤。现在我有一个用例,如果相同的API请求,如果请求主体不同,API响应需要不同。
{
id: 1
name: 'foo'
}
如果请求体是如下图所示,响应也会有所不同。
{
id: 2
name: 'bar'
}
有没有什么方法可以根据请求主体过滤请求,从而可以通过TestCafe相应地改变响应?感谢任何帮助。
你可以在你的 onRequestTo
. 我创建了一个简单的例子来演示它。
import { RequestMock } from 'testcafe';
fixture `Fixture`;
const mock = RequestMock()
.onRequestTo(request => {
console.log(request); // The full request object
return request.url.indexOf('google') > -1; // Here you can set your own rule
})
.respond((req, res) => {
res.setBody('<html><body><h1>OK</h1></body></html>');
});
test
.requestHooks(mock)
('test', async t => {
await t
.navigateTo('https://google.com')
.debug(); // Here we can see our mocked response
});
有一个选项可以通过一个谓词来过滤。https:/devexpress.github.iotestcafedocumentationreferencetest-apirequestmockonrequestto.html#select-requests-to-be-handled-by-thehook。
本页的其他过滤器有requestMock的例子,也有requestLogger的例子,但谓词只有requestLogger的例子。总之,检查一下是否有效。
谢谢大家的帮助。这真的帮助了我。我现在能够根据请求体过滤我的请求。我正在比较API请求体和我期望的json体,并在条件通过时嘲笑响应。我的代码现在是这样的。我正在比较缓冲区,因为 request.body
属于 buffer
.
const mock = RequestMock()
.onRequestTo(
request =>
request.url.match(/api\/assets\/.*\/staged-document/) &&
request.method === 'post' &&
!Buffer.compare(request.body, Buffer.from({"assetId":1,"name":"file1.name"}, 'utf-8')),
)
.respond({some response}, status, {
'access-control-allow-credentials': 'true',
'access-control-allow-methods': 'GET, POST, PUT, OPTIONS',
});