4

I recently started working on spring boot projects. I am looking for a way to assert the entire response of my API. The intention of this is to reduce the testing time taken for the API.

Found A few solutions mentioned below, but nothing helped me resolve the issue.

pm.test("Body matches string", function () {
    pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});


pm.test("Body is correct", function () {
    pm.response.to.have.body("response_body_string");
});

When I put the entire response body as an argument, I get the below errors.

  1. Unclosed String

2. enter image description here

3. enter image description here

Tushar Banne
  • 1,587
  • 4
  • 20
  • 38
  • Do you *need* to assert against a string? Your test is checking JSON but as a string, It doesn’t seem like a good approach. Why tag the question with JSON? – Danny Dainton Jan 02 '18 at 08:30

2 Answers2

1

If you want to use the same type of quotes you defined the string with inside it, you have to escape them:

  • 'string with "quotes"'
  • "string with 'quotes'"
  • 'string with \'quotes\''
  • "string with \"quotes\""

You probably want to put your json in single quotes as they are not allowed by json itself.

pishpish
  • 2,574
  • 15
  • 22
  • As *Postman* uses *JS* in *Tests/Pre-request Scripts*, you also can use a *grave accent*. Consider: `\`string with both 'single quotes' and "double quotes\`` – n-verbitsky Apr 14 '20 at 18:34
1

You could try setting the response as a variable and then assert against that?

var jsonData = pm.response.json()

pm.environment.set('responseData', JSON.stringify(jsonData))

From here you can get the data JSON.parse(pm.enviroment.get('responseData')) and then use this within any test to assert against all of the values.

pm.test("Body is correct", () => {
    var jsonData = pm.response.json()
    pm.expect(jsonData).to.deep.equal(JSON.parse(pm.environment.get('responseData')))
})

My reasoning is that you’re trying to assert against JSON anyway but doing as a plain text string.

Or you could assert against the values separately like this:

pm.test("Body is correct", () => {
    var jsonData = pm.response.json()
    pm.expect(jsonData[0].employeeName).to.equal("tushar")
    pm.expect(jsonData[0].phNum).to.equal(10101010)
})

Depending on the JSON structure you may not need to access an array of data and the [0] can be dropped.

Danny Dainton
  • 23,069
  • 6
  • 67
  • 80