如何在Cypress中拦截相同URL但不同Payload的API请求?
解决Cypress拦截同URL不同请求体API的方法
这里提供几种可行的实现方式,帮你区分这两个请求:
1. 路由匹配器中直接指定请求体规则
Cypress的cy.intercept支持在路由匹配器里通过body参数做部分匹配,精准拦截对应dataCategory的请求,给不同请求设置独立别名后就能分别断言:
// 拦截dataCategory为Hardware的请求 cy.intercept({ method: 'POST', url: 'http://localhost:8000/getdata/', body: { dataCategory: 'Hardware' } }).as('hardwareRequest') // 触发对应操作后等待并断言 cy.wait('@hardwareRequest').then(interception => { expect(interception.request.body.dataCategory).to.equal('Hardware') }) // 同理处理Software的请求 cy.intercept({ method: 'POST', url: 'http://localhost:8000/getdata/', body: { dataCategory: 'Software' } }).as('softwareRequest') cy.wait('@softwareRequest').then(interception => { expect(interception.request.body.dataCategory).to.equal('Software') })
2. 拦截回调中根据请求体标记别名
如果需要一次性拦截这个URL的所有请求,再区分不同请求体,可以在拦截回调里判断req.body的值,给不同请求设置不同别名,后续分别等待断言:
cy.intercept('POST', 'http://localhost:8000/getdata/', req => { if (req.body.dataCategory === 'Hardware') { req.alias = 'hardwareRequest' } else if (req.body.dataCategory === 'Software') { req.alias = 'softwareRequest' } }) // 触发两个请求后分别验证 cy.wait('@hardwareRequest').its('request.body.dataCategory').should('eq', 'Hardware') cy.wait('@softwareRequest').its('request.body.dataCategory').should('eq', 'Software')
3. 结合Spy函数区分请求
创建一个spy函数,在拦截时传入请求体,后续通过spy的调用记录来断言不同请求:
const requestSpy = cy.spy().as('requestSpy') cy.intercept('POST', 'http://localhost:8000/getdata/', req => { requestSpy(req.body) }) // 触发请求后检查spy的调用情况 cy.get('@requestSpy').should('have.been.calledWith', { dataCategory: 'Hardware' }) cy.get('@requestSpy').should('have.been.calledWith', { dataCategory: 'Software' })
内容的提问来源于stack exchange,提问作者Ronnie
相关产品推荐
相关产品推荐

