javascript - 使用 Cypress.io 捕获所有 XHR 请求
问题描述
当我调用 URL 时,会发送未定义数量的请求。
现在我尝试找出其中一个请求是否包含某个有效负载。
cy.server();
cy.visit(url);
cy.route({
method: 'POST',
url: '**/t/e/**',
}).as('xhrRequest');
我在How to capture all API calls in cypress? 上找到了类似的方法?至今。这里的问题是假定了固定数量的 API 调用。
cy.wait(Array(60).fill('@xhrRequest'), { timeout: 30000 }).then((xhrs) => {
xhrs.forEach((res) => {
expect(res.status).not.to.be.null
})
})
如果没有包含有效负载的单个请求,我如何获得所有请求都被拦截并且我的测试失败。
我已经在 puppeteer 中写过类似的东西
let hasSpecialRequest = false;
page.on('request', request => {
if (isSpecialRequest(request)) {
hasSpecialRequest = true;
}
request.continue();
});
await page.setRequestInterception(true);
expect(hasSpecialRequest).to.equal(true);
系统检查每个请求是否是特殊请求之一并相应地设置变量。我尝试用 Cypress 重新创建这样的东西。
解决方案
我可能误解了这个问题,但自从我通过谷歌探险来到这里,也许这可能会帮助遇到我的问题的人,也可能是你。
起初我使用cy.wait(@alias)
但无法检索所有响应(只显示一个响应,我无法弄清楚如何访问所有响应)。所以我最终立即将响应存储到另一个数组中以在测试中访问。
let xhrRequests;
function getXhrRequests() {
xhrRequests = [];
cy.intercept('GET', '**', (res) => {
xhrRequests.push(res);
});
return xhrRequests;
}
describe('Some', function () {
it('Thing 1', () => {
let thing1 = getXhrRequests();
cy.visit('http://some.site');
thing1.forEach((res) => {
expect(res.status).not.to.be.null;
})
}
it('Thing 2', () => {
let thing2 = getXhrRequests();
cy.visit('http://some.site/2');
thing2.forEach((res) => {
expect(res.status).not.to.be.null;
})
}
});
推荐阅读
- python - 添加列表元素
- node.js - 当堆栈跟踪对于标准输出来说太大时,如何获取 NodeJS 错误?
- c++ - Win32Api 窗口菜单激活问题
- dataframe - 我可以使用 DataFrames 在 Julia 中按天或按月分组吗
- python - 清理将每条记录视为表的数据集
- python - 从每个句子末尾的括号中的文本中提取日期
- python - is the connection/cursor object automatically closed in SQLAlchemy
- android - 如何更改 SearchView 的文本颜色?
- spring-boot - 间歇性 java.net.SocketException:来自服务器的文件意外结束
- amazon-cloudwatch - Cloudwatch 仪表板 - 从条形图中隐藏 x 轴标签