测试咖啡馆 - 如何修改数据或将数据注入响应?



在TestCafe中,我们有RequestHooks和RequestMocks。我希望我的页面为 TestCafe 进行 API 调用添加,以将一条数据添加到返回的响应中。

到目前为止,我拥有的:

import { RequestHook, RequestMock } from 'testcafe';
// option 1: RequestHook
class ModifyRequest extends RequestHook {
constructor (requestFilterRules) {
super(requestFilterRules, { includeBody: true });
}
async onRequest (event) {
// ...
}
async onResponse (event) {
const copy = JSON.parse(event.body.toString());
copy.test = 'test';
event.body = Buffer.from(JSON.stringify(copy), 'utf8');
// doesn't actually modify the response
}
}
// option 2: RequestMock
export const modifyRequest = RequestMock()
.onRequestTo(/processing/)
.respond((req, res) => {
console.log(res); // actual response not available
res.setBody({
data: 'original data here'
});
});

如何实际进行 API 调用并向响应添加数据?

据我了解,您只想嘲笑部分响应。目前,您无法使用RequestHooks机制执行此操作。RequestMock修改完整响应,RequestHook不允许您修改响应body

你需要将你的 RequestMock 作为一个钩子添加到你的灯具中:

fixture`<fixture-name>`
.page(<url>)
.requestHooks(modifyRequest);

完整示例如下:https://github.com/proustibat/xke-introduction-testcafe/blob/58eb6b51548ae1d9498c853ee8f8b748e5623218/e2e/index.js#L64

最新更新