使用Cypress访问Tutorialspoint时页面加载超时问题求助
解决Cypress访问网站超时及终止加载的方案
1. 拦截请求终止不必要的加载
直接用cy.intercept拦截广告、统计这类非核心资源,同时手动触发load事件绕过超时:
// 拦截并取消非必要请求 cy.intercept('**/*', (req) => { const unwantedKeywords = ['ad', 'analytics', 'tracking'] if (unwantedKeywords.some(keyword => req.url.includes(keyword))) { req.abort() } }) cy.visit('https://www.tutorialspoint.com/html/index.htm', { onBeforeLoad(win) { // 手动触发load事件,避免Cypress超时 setTimeout(() => { win.dispatchEvent(new Event('load')) }, 1500) } })
2. 修正baseURL配置解决视口问题
baseURL应该只配置域名,别带具体页面路径:
// cypress.config.js里的配置 module.exports = defineConfig({ e2e: { baseUrl: 'https://www.tutorialspoint.com', }, }) // 访问页面时用相对路径 cy.visit('/html/index.htm') // 强制设置视口匹配原网站 cy.viewport(1920, 1080)
3. 直接手动标记文档为完成状态
如果页面已经渲染好了但load事件没触发,直接修改文档状态:
cy.visit('https://www.tutorialspoint.com/html/index.htm', { failOnStatusCode: false }) cy.document().then(doc => { doc.readyState = 'complete' }) // 接下来就可以正常做元素验证了 cy.get('.main-heading').should('be.visible')
4. 临时调整超时时间(备选)
如果只是部分资源加载慢,临时调大超时:
cy.visit('https://www.tutorialspoint.com/html/index.htm', { pageLoadTimeout: 100000 // 设为100秒 })
内容的提问来源于stack exchange,提问作者user3303019
相关产品推荐
相关产品推荐

