How to use files to store data used by test cases

I want to run a test case, where the result of the call should be compared to another result.

// Check that the response body matches the required response
pm.test("body is correct", function () {
    pm.expect(pm.response.json()).to.eql("Response Test");
});

However, this response text is a very big string and should probably not be simply pasted in the test code, but saved in a file.

How can I do something like this?

Hey @patrickgrenier :wave:

Welcome to the Postman Community! :postman:

You could store that in a variable, away from the test code and reference that in there?

For example:

let matchedString = pm.variables.get('matchedString');
// Check that the response body matches the required response
pm.test("body is correct", function () {
    pm.expect(pm.response.json()).to.eql(matchedString);
});

You could add it to an external datafile and have a placeholder reference in the test but that’s only going to work in the Collection Runner context.

Using Newman as a library and creating a script could be another option, the response could be in a separate file and you can inject that into the Collection with the Newman script. That’s a bit more involved though.

Testing the whole response like this in one go can be difficult to troubleshoot if\when it fails.

If there is more than one issue in the response, you won’t get the feedback on all of the elements that have issues.

Even if you only have one issue, that will probably be also difficult to ascertain from the failing test where exactly its failing.

All you will really know is that the two don’t match somewhere.

A well designed test should tell you exactly what is wrong.

You might want to consider jsonSchema tests to confirm that the structure of the response is correct.

Personally, I would have separate tests for each element in the response that is important to me.

I would minify the JSON for the expected result, and then store it as a collection variable.

Depending on the JSON structure, it might be one loop or multiple loops through that collection variable checking each element. This will then make the tests individual and provide feedback on all failing elements.

Of course, I don’t know how large your response is, so this might be unfeasible due to size.

Do you have an example response, so I can show how this might work in practice?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.