如何在Cypress页面加载卡住时继续执行剩余脚本?
在Cypress页面加载卡住时继续执行脚本的解决方案
针对你遇到的页面加载卡住导致cy.wait('@authRequest')后续代码无法执行的问题,以下是几个实用的解决方法:
1. 拦截auth请求后立即终止页面加载
在拦截到目标auth请求并确认请求完成后,直接调用浏览器的stop()方法终止页面剩余加载流程,避免页面卡住:
describe('Fetching auth data', () => { it('proccess cookies and send to the API', () => { cy.clearCookies(); cy.intercept({ method: 'GET', url: 'https://my.auth.request' }, (req) => { req.continue(); // 确保auth请求正常完成 // 立即停止页面加载 cy.window().then(win => win.stop()); }).as('authRequest'); cy.visit('https://wanted.login.page'); cy.get('input[id=username]').type(`${Cypress.env('username')}{enter}`); cy.get('input[id=password]').type(`${Cypress.env('password')}{enter}`); cy.wait('@authRequest').then((inter) => { let cookies // 提取Cookie等逻辑... // 发送Cookie到后端 cy.request({ method: 'POST', url: `${Cypress.env('apiURL')}/webhooks`, json: true, headers: { 'X-App-Token': Cypress.env('webhookToken'), }, body: { cookie: formattedCookies, }, }); }); }); });
2. 给cy.visit设置加载超时
通过修改cy.visit的配置,设置页面加载超时时间,超时后Cypress会自动跳过等待,继续执行后续脚本:
cy.visit('https://wanted.login.page', { pageLoadTimeout: 10000, // 设置10秒超时,按需调整 failOnStatusCode: false // 忽略页面状态码错误(如果有的话) });
3. 调整Cypress全局页面加载超时
在cypress.config.js中修改全局的页面加载超时配置,替换默认的60秒超时,避免因页面长时间加载卡住整个测试:
const { defineConfig } = require('cypress'); module.exports = defineConfig({ e2e: { pageLoadTimeout: 15000, // 设置为15秒,可根据实际情况调整 // 其他e2e配置项... } });
4. 绕过页面加载,直接在拦截回调中处理逻辑
不需要等待页面加载完成,直接在auth请求的拦截响应回调中提取Cookie并发送到后端,完全避开页面加载卡住的问题:
describe('Fetching auth data', () => { it('proccess cookies and send to the API', () => { cy.clearCookies(); cy.visit('https://wanted.login.page'); cy.intercept({ method: 'GET', url: 'https://my.auth.request' }, (req) => { req.continue((res) => { // 从响应头提取Set-Cookie并格式化 const setCookieHeader = res.headers['set-cookie']; const formattedCookies = setCookieHeader?.map(cookie => cookie.split(';')[0]).join('; ') || ''; // 直接发送到后端 cy.request({ method: 'POST', url: `${Cypress.env('apiURL')}/webhooks`, json: true, headers: { 'X-App-Token': Cypress.env('webhookToken'), }, body: { cookie: formattedCookies, }, }); }); }); cy.get('input[id=username]').type(`${Cypress.env('username')}{enter}`); cy.get('input[id=password]').type(`${Cypress.env('password')}{enter}`); }); });
内容的提问来源于stack exchange,提问作者Aldinho
相关产品推荐
相关产品推荐

