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

如何在Cypress测试中获取并校验发送的请求数据?

嘿,这个场景我熟!要在Cypress里校验创建请求的请求体,核心是先用cy.intercept()提前监听目标请求,再触发创建动作,最后通过拦截到的请求对象获取请求体做断言。我给你一步步拆解怎么做:

第一步:提前拦截目标请求

在你填充表单、点击「创建」按钮之前,就要用cy.intercept()注册对创建接口的监听。记得给这个拦截起个别名(比如@createProject),方便后续引用。

假设你的后端接口是POST /api/projects,代码大概是这样:

// 注册拦截,替换成你实际的接口URL
cy.intercept('POST', '/api/projects').as('createProject');

如果你的接口URL是动态的(比如带版本号或者参数),可以用正则匹配,比如:

cy.intercept('POST', /\/api\/v1\/projects/).as('createProject');

第二步:执行表单填充与创建操作

这部分就是你已经完成的步骤:自动填充表单里的URL、令牌、密码等信息,然后点击「创建」按钮。建议把测试数据提前定义成变量,方便复用和维护:

const testData = {
  url: 'https://test-project.example.com',
  tokens: 'test-token-123',
  password: 'test-pass-456',
  sshInfo: {
    host: '192.168.0.100',
    username: 'dev-user',
    port: 22
  },
  projectName: 'My Test Project'
};

// 填充表单(选择器替换成你实际的元素标识)
cy.get('[data-testid="url-input"]').type(testData.url);
cy.get('[data-testid="token-input"]').type(testData.tokens);
cy.get('[data-testid="password-input"]').type(testData.password);
cy.get('[data-testid="ssh-host"]').type(testData.sshInfo.host);
cy.get('[data-testid="ssh-username"]').type(testData.sshInfo.username);
cy.get('[data-testid="project-name"]').type(testData.projectName);

// 点击创建按钮
cy.get('[data-testid="create-button"]').click();

第三步:等待请求完成并校验请求体

用cy.wait()等待刚才拦截的请求完成,然后通过拦截对象的request.body获取请求体,接着就可以做各种断言了:

cy.wait('@createProject').then((interception) => {
  // 取出请求体(Cypress会自动解析JSON格式的请求体为对象)
  const requestBody = interception.request.body;

  // 校验单个字段
  expect(requestBody.url).to.equal(testData.url);
  expect(requestBody.tokens).to.equal(testData.tokens);
  expect(requestBody.password).to.equal(testData.password);
  // 嵌套对象要用deep.equal来校验完整结构和值
  expect(requestBody.sshInfo).to.deep.equal(testData.sshInfo);
  expect(requestBody.projectName).to.equal(testData.projectName);

  // 也可以直接校验整个请求体和测试数据是否完全一致
  // expect(requestBody).to.deep.equal(testData);
});

一些实用小提示

  • 如果你的请求体不是JSON格式(比如form-data),需要手动解析:JSON.parse(interception.request.body)
  • 如果请求可能有延迟,可以给cy.wait()加超时时间,比如cy.wait('@createProject', { timeout: 10000 })
  • 要确保拦截的HTTP方法(POST)和URL完全匹配,否则会监听不到目标请求

内容的提问来源于stack exchange,提问作者Mustafa Yaşar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 20:52:40