赛普拉斯 POST 请求,如何访问响应正文的 'fields' 部分

Cypress POST request, how to access 'fields' section of reponse body

我想在 Cypress 中发送一个 POST 请求,触发验证以拒绝请求

根据 Postman 的说法,响应正文如下所示:

    "code": "validation_error",
    "message": "Validation error, please see fields property for details",
    "fields": 
    {
        "TariffData[rate_gp]": " Invalid rate_gp. Expected: 9.35. Imported: 19.35"
    }

我对“字段”部分感兴趣,所以我尝试用这段代码断言:

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).to.contain('"TariffData[rate_gp]": " Invalid rate_gp. Expected: 9.35. Imported: 19.35"')
                    })
  )}
)}

然而这会导致错误:

AssertionError

object tested must be an array, a map, an object, a set, a string, or a weakset, but object given

是的,错误消息到此结束。我有什么想法可以断言响应包含此消息吗?

我认为您只想将预期值呈现为对象,而不是字符串

  expect(response.body.fields)
    .to.contain({
      "TariffData[rate_gp]": " Invalid rate_gp. Expected: 9.35. Imported: 19.35"
    })

如果您查看文档 chaijs API 他们显示,例如

expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2});

containinclude

的同义词

您也可以尝试 to.deep.equal,因为您指定的总数似乎是 fields 属性

  expect(response.body.fields)
    .to.deep.eq({
      "TariffData[rate_gp]": " Invalid rate_gp. Expected: 9.35. Imported: 19.35"
    })