cy.intercept返回结果始终为大写的问题排查与解决
问题原因及解决方案
可能的原因
- 前端响应拦截器处理:项目中可能使用了Axios这类HTTP客户端的响应拦截器,接收API响应后自动将
firstName转为大写,而Postman直接获取原始API响应,因此两者结果不同。 - API根据请求头返回不同格式:API可能依据请求中的
User-Agent、Accept等头字段返回不同内容,Cypress默认请求头与Postman不一致,导致返回大写的firstName。 - 其他测试代码修改了响应:项目内其他地方的
cy.intercept可能对同一API做了mock,强制返回大写firstName,覆盖了原始响应。
排查与解决步骤
步骤1:确认原始API响应内容
通过cy.intercept回调打印原始响应,判断问题出在API还是前端处理:
cy.intercept('GET', '/api-customers/welcome', (req) => { req.continue((res) => { console.log('原始API响应:', res.body); // 浏览器控制台查看firstName实际值 }); }).as('getAPIwelcome'); cy.wait('@getAPIwelcome').then((interception) => { validatePageContents(interception); });
- 若控制台输出
firstName为Jonathan,说明是前端后续处理成了大写; - 若输出为
JONATHAN,说明API本身返回大写,问题出在请求头或API逻辑。
步骤2:处理前端拦截器转换问题
如果是前端响应拦截器将firstName转成大写,可在断言前将获取到的custName转换为首字母大写格式:
export const validatePageContents = (getAPIwelcome) => { const custName = getAPIwelcome.response?.body.firstName; // 转换为首字母大写格式 const formattedName = custName.charAt(0).toUpperCase() + custName.slice(1).toLowerCase(); cy.get(element).should('contain', formattedName); };
步骤3:统一请求头解决API返回差异
如果API根据请求头返回不同内容,将Cypress的请求头修改为与Postman一致:
cy.intercept('GET', '/api-customers/welcome', (req) => { // 复制Postman中的请求头,示例如下 req.headers['User-Agent'] = 'PostmanRuntime/7.32.3'; req.headers['Accept'] = 'application/json'; }).as('getAPIwelcome');
步骤4:检查是否存在mock覆盖响应
搜索项目内所有cy.intercept('/api-customers/welcome')代码,排查是否有强制返回大写firstName的mock逻辑,比如:
// 此类代码会覆盖原始响应,需移除或修改 cy.intercept('GET', '/api-customers/welcome', { body: { firstName: 'JONATHAN' } });
内容的提问来源于stack exchange,提问作者Jonathan Oliveira
相关产品推荐
相关产品推荐

