首页 > 解决方案 > Cypress 捕获所有请求 cy.Route()

问题描述

在此处输入图像描述在此处输入图像描述

我想捕获所有请求,但cy.Route()似乎不接受通配符。因此,例如,我想导航到 Reddit”并捕获所有请求,但是,我还希望代码可重用,以便我可以导航到堆栈溢出并捕获所有请求。

这可能吗?

我试过 * 通配符,但它不起作用

cy.route('*').as('GETS');

cy.route(GET, '*').as('GETS');

标签: javascriptcypress

解决方案


Cypress自动包含 minimatch 并将其公开为 Cypress.minimatch。根据minimatch 文档,您需要使用"Globstar" ** matching

get所有和post请求的正确方法:

cy.route('GET', '**').as('gets'); cy.route('POST', '**').as('posts');

或者,

cy.route({
    method: 'GET',
    url: '**'
}).as('gets');


cy.route({
    method: 'POST',
    url: '**'
}).as('posts');

注意:cy.route() should be set before cy.visit()。要阅读响应,请使用cy.wait('@gets').thency.wait('@posts').then

cy.wait('@posts').then((xhr) => {
    cy.log('Intercepted: ' + xhr.url);
    cy.log('Intercepted: ' + JSON.stringify(xhr.response.body));
});

测试www.google.com

测试截图

测试www.instagram.com测试截图


推荐阅读