KVN
KVN

Reputation: 982

Postman - how to get "message" when POST request returns 400 Error

I have a POST request in Postman, with the following test

pm.test("CREATED - Status code is 201", function () {
    pm.response.to.have.status(201);
});

var namespaceLink = postman.getResponseHeader("Location");
var namespaceId = namespaceLink.substring(namespaceLink.lastIndexOf('/') + 1);

pm.environment.set("IdOfNamespace", namespaceId);

The request is failing with "400 Bad Request". In this case, I would expect that Test fails with something like "Expected 201 but got 400", but the test is failing with following "There was an error in evaluating the test script: TypeError: Cannot read property 'substring' of undefined" I also receive the following message in the response body: "Namespace 'AUTO_NS' is already using this code"

Since the request is run as part of the automated test (with a lot of requests) and then generate a report, I would like to set up the test the way it will be more clear in the report on the reason of the failure. I.e. message from response body.

Can you please help me on how I can do it (as part of the test)?

Upvotes: 0

Views: 1254

Answers (1)

n-verbitsky
n-verbitsky

Reputation: 552

You just can simply have your code inside the test function. When your pm.response.to.have.status(201); assertion fails, chai throws AssertionError and that means that the other lines inside your test function won't be executed. In other cases, you're good to go. Try this:

pm.test("CREATED - Status code is 201", () => {
    pm.response.to.have.status(201);
    const namespaceLink = postman.getResponseHeader("Location");
    const namespaceId = namespaceLink.substring(namespaceLink.lastIndexOf('/') + 1);
    pm.environment.set("IdOfNamespace", namespaceId);
});

Upvotes: 1

Related Questions