如何在Cypress中查看所有已存根端点?运行时快速列出已存根路由
在Cypress中查看已存根端点/路由的可行方案
方法1:直接访问Cypress内部状态(适配cy.intercept())
Cypress会将所有通过cy.intercept()配置的存根路由存储在内部配置中,你可以在运行时直接获取:
- 在测试代码中打印:
cy.then(() => { const allStubbedRoutes = window.top.Cypress.config('intercepts') || []; console.log('所有已存根路由:', allStubbedRoutes); }); - 也可以在Cypress测试运行器的开发者工具控制台中直接输入:
window.top.Cypress.config('intercepts')
返回的数组包含每个存根路由的method、url、alias等核心信息,能快速确认已配置的存根规则。
方法2:自定义命令统一收集存根路由
如果需要更灵活的跟踪,可以实现自定义命令来主动记录所有存根操作:
- 在
cypress/support/commands.js中添加以下代码:const stubbedRoutes = []; Cypress.Commands.add('stubRoute', (method, url, options = {}) => { // 记录路由信息 stubbedRoutes.push({ method, url, alias: options.alias }); // 调用原生intercept完成存根 return cy.intercept(method, url, options); }); // 添加查看所有存根路由的命令 Cypress.Commands.add('listStubbedRoutes', () => { cy.wrap(stubbedRoutes).then(routes => { console.log('已存根路由列表:', routes); return routes; }); }); - 在测试中用自定义命令替代原生
cy.intercept():cy.stubRoute('GET', '/api/users', { alias: 'fetchUsers' }); cy.stubRoute('POST', '/api/login', { alias: 'userLogin' }); // 查看所有存根路由 cy.listStubbedRoutes();
方法3:通过Cypress测试运行器UI查看
在Cypress测试运行器的Network标签页中,所有被存根拦截的请求会被标记为(Stubbed),你可以直观看到请求的方法、URL、别名及状态,这是最便捷的可视化查看方式。
内容的提问来源于stack exchange,提问作者YellowGuy
相关产品推荐
相关产品推荐

