Cypress POST请求中如何正确断言响应体fields字段内容?
解决Cypress中POST请求响应体fields字段的断言问题
我来帮你搞定这个Cypress断言的问题!你遇到的AssertionError是因为response.body.fields是一个JavaScript对象,而你用contain去匹配字符串格式的键值对——contain方法适用于数组、字符串这类可遍历的类型,对象得用对象专属的断言方式来处理。
错误原因分析
你之前的代码里,尝试用expect(response.body.fields).to.contain(...)去匹配一个字符串化的键值对,但fields是一个结构如下的对象:
{ "TariffData[rate_gp]": " Invalid rate_gp. Expected: 9.35. Imported: 19.35" }
直接对对象用contain会触发类型不匹配的错误。
正确的断言写法
你可以针对对象的键和对应的值分别做断言,这里有几种常用的方式:
1. 精确匹配字段的错误信息
如果你需要完全校验该字段的错误文本,可以直接通过键名获取值后断言:
.then(response => { expect(response.status).to.eq(400) // 直接通过对象键名获取对应错误信息并断言 expect(response.body.fields['TariffData[rate_gp]']).to.eq(' Invalid rate_gp. Expected: 9.35. Imported: 19.35') })
2. 模糊匹配错误文本(校验包含特定内容)
如果你只需要确认错误信息包含关键内容(比如预期值、导入值),可以用include:
.then(response => { expect(response.status).to.eq(400) expect(response.body.fields['TariffData[rate_gp]']).to.include('Expected: 9.35') expect(response.body.fields['TariffData[rate_gp]']).to.include('Imported: 19.35') })
3. 先校验字段存在,再校验内容
如果需要先确保fields对象包含目标字段,再校验内容:
.then(response => { expect(response.status).to.eq(400) // 确认fields对象有这个属性 expect(response.body.fields).to.have.property('TariffData[rate_gp]') // 再校验属性值包含指定内容 expect(response.body.fields['TariffData[rate_gp]']).to.contain('Invalid rate_gp') })
完整修正后的代码
const api_key = require('../../fixtures/contracts/api_test_client1.json') const body1 = require('../../fixtures/contracts/body_test_client1.json') describe('test POST/client validation', () => { it('send POST/client request', function () { cy.request({ method: 'POST', url: Cypress.env('staging_url') + '/service/clients', headers: { 'API-KEY': api_key, }, body: body1, failOnStatusCode: false }) .then(response => { expect(response.status).to.eq(400) // 这里用精确匹配的方式,你可以根据需求换成上面的其他写法 expect(response.body.fields['TariffData[rate_gp]']).to.eq(' Invalid rate_gp. Expected: 9.35. Imported: 19.35') }) }) })
内容的提问来源于stack exchange,提问作者cypher_null
相关产品推荐
相关产品推荐

