You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中反序列化JSON请求并断言响应体对象?

在Cypress中处理JSON响应并执行断言

其实Cypress在处理JSON格式的响应时,会自动帮你反序列化(解析)成JavaScript对象,不需要手动做额外的解析步骤。不过还是给你几种常见场景的处理方式,确保你能顺利对响应体做断言:

场景1:直接使用cy.request()发起请求

如果你是用cy.request()调用接口,它返回的响应里的body已经是解析好的JSON对象了,直接拿来断言就行:

cy.request('GET', '/your-api-endpoint')
  .then((response) => {
    // 这里response.body已经是解析后的JSON对象
    expect(response.body).to.have.property('physicalID', 'Physical file updated');
    expect(response.body.fileData).to.be.null;
  });

场景2:拦截网络请求(使用cy.intercept())

如果你是通过拦截请求来获取响应,同样拦截到的响应体也会被自动解析:

cy.intercept('GET', '/your-api-endpoint').as('getUpdatedFile');

// 触发请求的操作,比如点击按钮或者访问对应页面
cy.visit('/your-page');

cy.wait('@getUpdatedFile').then((interception) => {
  // interception.response.body 是解析好的JSON对象
  expect(interception.response.body.physicalID).to.eq('Physical file updated');
  expect(interception.response.body.fileData).to.be.null;
});

特殊情况:响应未被自动解析(比如返回JSON字符串)

如果遇到极少数情况,响应体还是原始的JSON字符串(比如接口返回的Content-Type不是application/json),那你可以手动用JSON.parse()来解析:

cy.request('GET', '/your-api-endpoint')
  .then((response) => {
    // 手动解析JSON字符串
    const parsedBody = JSON.parse(response.body);
    expect(parsedBody.physicalID).to.eq('Physical file updated');
    expect(parsedBody.fileData).to.be.null;
  });

另外,你可以先打印响应体确认结构,看看是不是已经解析好的对象:

cy.request('GET', '/your-api-endpoint')
  .then((response) => {
    console.log(response.body); // 在控制台查看响应体的类型和内容
  });

这样应该就能顺利完成你想要的断言操作啦~

内容的提问来源于stack exchange,提问作者ashna naran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:29:18