Home > Software engineering >  Cypress POST request, how to access 'fields' section of reponse body
Cypress POST request, how to access 'fields' section of reponse body

Time:10-19

I want to send a POST request in Cypress that triggers the validation to reject the request

According to Postman, the body of the response looke like this:

    "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"
    }

I am interested in the "fields" section, so I tried to assert with this code:

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"')
                    })
  )}
)}

Yet this leads to an error:

AssertionError

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

Yes, the error message ends there. Any ideas how I can make an assertion that the response contains this message?

CodePudding user response:

I think you just want to present the expected value as an object, not as a string

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

If you looks at the docs chaijs API they show, for example

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

and contain is a synonym for include

You could also try to.deep.equal, as it seems you are specifying the total fields property

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