如何在Cypress中遍历同一路由的多个别名?
校验Cypress中多次匹配的API请求Payload
针对同一API端点被两次调用的场景,有几种实用方法可以分别校验每个请求的payload:
方法1:按顺序多次调用cy.wait()
cy.wait('@alias')会按请求触发的顺序依次匹配拦截到的请求,因此可以连续调用两次,分别对每个请求做断言:
// 先定义路由拦截 cy.intercept({ method: 'POST', url: `${Cypress.env('API_URL')}/api/v1/company/*/statistics/charts/data?cache_buster=*`, }).as('chartData'); // 触发仪表盘加载(比如访问页面) cy.visit('/dashboard'); // 校验第一个请求的payload cy.wait('@chartData').then((interception) => { expect(interception.response.statusCode).to.eq(200); expect(interception.request.body.document_types).to.deep.eq(['receipt', 'invoice']); expect(interception.request.body.filters[0]).to.deep.eq({ comparison_operator: '==', field: 'purchase_date', type: 'field_value', value: 'this_year' }); }); // 校验第二个请求的payload cy.wait('@chartData').then((interception) => { expect(interception.response.statusCode).to.eq(200); // 替换为第二个请求的实际断言逻辑 expect(interception.request.body.document_types).to.deep.eq(['expense_report']); expect(interception.request.body.filters[0].value).to.eq('last_month'); });
方法2:收集所有请求后统一校验
如果需要等待所有请求完成后再批量校验,可以用数组记录所有请求,待请求全部完成后断言:
const chartRequests = []; cy.intercept({ method: 'POST', url: `${Cypress.env('API_URL')}/api/v1/company/*/statistics/charts/data?cache_buster=*`, }, (req) => { req.continue((res) => { // 收集请求和响应信息 chartRequests.push({ requestBody: req.body, statusCode: res.statusCode }); }); }).as('chartData'); // 触发请求 cy.visit('/dashboard'); // 等待两个请求全部完成 cy.wait('@chartData').wait('@chartData').then(() => { // 先校验请求总数 expect(chartRequests.length).to.eq(2); // 校验第一个请求 expect(chartRequests[0].statusCode).to.eq(200); expect(chartRequests[0].requestBody.document_types).to.deep.eq(['receipt', 'invoice']); // 校验第二个请求 expect(chartRequests[1].statusCode).to.eq(200); expect(chartRequests[1].requestBody.filters[0].value).to.eq('last_month'); });
方法3:根据请求特征设置不同别名
如果两个请求的payload有明确区分特征,可以在拦截时根据内容设置不同别名,实现精准匹配:
// 拦截第一个请求(匹配特定document_types) cy.intercept({ method: 'POST', url: `${Cypress.env('API_URL')}/api/v1/company/*/statistics/charts/data?cache_buster=*`, body: { document_types: ['receipt', 'invoice'] } }).as('firstChartData'); // 拦截第二个请求(匹配另一组document_types) cy.intercept({ method: 'POST', url: `${Cypress.env('API_URL')}/api/v1/company/*/statistics/charts/data?cache_buster=*`, body: { document_types: ['expense_report'] } }).as('secondChartData'); // 触发请求 cy.visit('/dashboard'); // 分别校验两个请求 cy.wait('@firstChartData').then((interception) => { expect(interception.response.statusCode).to.eq(200); // 第一个请求的断言 }); cy.wait('@secondChartData').then((interception) => { expect(interception.response.statusCode).to.eq(200); // 第二个请求的断言 });
内容的提问来源于stack exchange,提问作者Peter Boomsma
相关产品推荐
相关产品推荐

