javascript - 如何在 testcafe 脚本中添加递归函数检查 xhr 响应?
问题描述
我正在尝试编写一个测试下载作品,它需要检查 xhr 响应是否有状态 READY。我使用 Promise 在 TestCafe 中创建了一个客户端函数,但在递归的情况下它会失败。
我应该如何修复我的代码来处理这种情况?
PS对新手的问题表示歉意,我刚刚开始了我的自动化测试之旅。
fixture`Download report works`
test
.requestHooks(logger)//connected a request hook, will wait for logger request
('I should be able to download PDF report from header of the page', async t => {
//recursively check if response status is READY, and then go to assertions
const waitForDownloadResponseStatus = ClientFunction((log) => {
return new Promise((resolve,rejects)=>{
const waitForStatus=()=>{
const arrayFromResponse = JSON.parse(log.response.body);
const responseStatus = arrayFromResponse.status;
if (responseStatus == 'READY')
{
resolve(responseStatus);
}
else {
waitForStatus();
}
}
waitForStatus();
})
});
//page objects
const reportTableRaw = Selector('div.contentcontainer').find('a').withText('April 2019').nth(0);
const downloadPdfButton = Selector('a.sr-button.sr-methodbutton.btn-export').withText('PDF');
//actions.
await t
.navigateTo(url)
.useRole(admin)
.click(reportTableRaw)//went to customise your report layout
.click(downloadPdfButton)
.expect(logger.contains(record => record.response.statusCode === 200))
.ok();//checked if there is something in logger
const logResponse = logger.requests[0];
// const arrayFromResponse = JSON.parse(logResponse.response.body);
// const responseStatus = arrayFromResponse.status;
console.log(logger.requests);
await waitForDownloadResponseStatus(logResponse).then((resp)=>{
console.log(resp);
t.expect(resp).eql('READY');
});
});
解决方案
当您将对象作为参数或依赖项传递给客户端函数时,它将接收传递对象的副本。因此它将无法检测到外部代码所做的任何更改。在这种特殊情况下,waitForStatus
函数不会达到其终止条件,因为它无法检测到log
外部请求挂钩对对象所做的更改。这意味着这个函数将无限期地运行,直到它耗尽所有可用的堆栈内存。之后,它将因堆栈溢出错误而失败。
READY
为避免这种情况,您可以在更改函数的谓词参数时检查响应是否具有状态contains
。看看下面的代码:
.expect(logger.contains(record => record.response.statusCode === 200 &&
JSON.parse(record.response.body).status === 'READY'))
.ok({ timeout: 5000 });
此外,您可以使用该timeout
选项。这是在测试失败之前断言可以通过的时间(以毫秒为单位)。
推荐阅读
- python - 如何使用 python 向电报机器人发送消息?
- python - 如何使用 python 正则表达式从网站恢复十进制字符串
- angular - ng-boostrap datepicker 中是否有任何 Blur 事件?
- python - 更新了终端上的 python 脚本 - 未反映更改
- java - 如何在 Java 类中实现 Kotlin 挂起方法?
- python - 从 R 转换为 python 时列表索引出错
- applescript - 在 Automator 中搜索所有外部驱动器
- android - 如何从按钮将列表视图发送到 Mysql 数据库?
- shopify - 如何在 Shopify 的自定义产品中禁用选定的时间段?
- sql - 在 Access 中显示较长的列名称