首页 > 解决方案 > 使用 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 重新创建这样的东西。

标签: javascriptcypress

解决方案


我可能误解了这个问题,但自从我通过谷歌探险来到这里,也许这可能会帮助遇到我的问题的人,也可能是你。

起初我使用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;
        })
    }
});

推荐阅读