Cypress拦截API返回固定JSON后页面加载失败问题求助
Cypress拦截API返回固定响应后出现“Failed to load”错误
我正在学习Cypress,尝试拦截API请求并返回固定JSON响应。拦截后所有响应均已正确发送,页面也能在IDE中正常加载,但Cypress却返回“Failed to load”错误。
测试代码
it.only('mocking api with intercept using static response', function(){ cy.intercept({ method: 'GET', // route all GET calls url: '/typicode/demo' // that go to this URL }, { body: ['forcing response to be this'] } // and force response to be this ).as('demo') cy.visit('https://my-json-server.typicode.com/', { failOnStatusCode: false }) cy.get('.hero > .container > .action > .button').click() cy.wait('@demo').its('response.statusCode').should('eq', 200); })
IDE界面

Network标签页情况

该网站为模拟站点,可复现问题,恳请帮忙排查。
排查与解决方法
1. 响应格式不匹配(核心问题)
原页面请求/typicode/demo后,预期接收的是包含结构化对象的数组(如[{id:1, title:"..."}]),但你返回的是简单字符串数组['forcing response to be this'],导致页面渲染时无法解析预期字段,触发前端JS异常,进而被Cypress判定为“Failed to load”。
修改响应为与原接口一致的格式:
cy.intercept({ method: 'GET', url: '/typicode/demo' }, { body: [ { id: 1, title: 'Mocked Demo Item' }, { id: 2, title: 'Another Mocked Item' } ] }).as('demo')
2. 验证拦截是否生效
可以在拦截逻辑中添加日志,确认请求被正确捕获:
cy.intercept({ method: 'GET', url: '/typicode/demo' }, (req) => { console.log('Request intercepted:', req.url) // 控制台输出确认 req.reply({ body: [ { id: 1, title: 'Mocked' } ] }) }).as('demo')
3. 忽略页面未捕获异常(临时方案)
如果需要保留自定义响应格式,可在测试开头添加代码忽略页面抛出的异常:
Cypress.on('uncaught:exception', () => { // 阻止Cypress因页面异常标记测试失败 return false })
4. 确认URL匹配规则
当前相对路径/typicode/demo匹配是正确的,但如果存在子域名或路径变化,可改用完整URL或通配符:
url: 'https://my-json-server.typicode.com/typicode/demo' // 完整URL // 或 url: '**/typicode/demo' // 通配符匹配任意前缀下的该路径
内容的提问来源于stack exchange,提问作者Ariha
相关产品推荐
相关产品推荐

