I want to check if an answer is ok. It is either correct when the response code is 200 or 500. Latter needs to differentiate between a String in the response body to be correct or incorrect. It should be in a single test.
I already tried simple if-clauses, but they do not work.
pm.test("response is ok", function(){
if(pm.response.to.have.status(200)){
//do things
}
});
The Solution i used is
pm.test("response is valid", function(){
if(pm.response.code === 200){
//is ok
} else if (pm.response.code === 500){
if(pm.expect(pm.response.json().message).to.include("xyz")){
//is ok
} else {
pm.expect.fail("Error 500");
}
} else {
pm.expect.fail("statuscode not 200 or 500");
}
});
This would be something basic that would log that message to the console if the status code was 200
:
pm.test('Check Status', () => {
if(pm.response.code === 200) {
console.log("It's 200")
}
})
If you then needed to check something in the response body
after, you could do something like the example below.
This is just sending a simple GET
request to http://jsonplaceholder.typicode.com/posts/1
The response body of this would be:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
We can add a check in the Tests
tab, to confirm that the id
property has a value of 1
, it would only run this check if the response code
was 200
:
if(pm.response.code === 200) {
pm.test('Check a value in the response', () => {
pm.expect(pm.response.json().id).to.eql(1)
})
}
This is a very basic and a very simple example of what you could do. It would be more complex depending on your own context but hopefully it explains how you could do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With