I need to check if the current request method is in an array with other methods. This test works:
if ((pm.request.method === "GET") || (pm.request.method === "HEAD")){
pm.test("Verify that the GET and HEAD methods are not deactivated", function () {
pm.expect(pm.response.code).to.not.eql(405);
});
}
I tried to write it differently, but this code doesn’t work:
if (pm.expect(pm.request.method).to.contain.oneOf(['GET', 'HEAD'])) {
pm.test("Verify that the GET and HEAD methods are not deactivated", function () {
pm.expect(pm.response.code).to.not.eql(405);
});
}
The error:
There was an error in evaluating the test script: AssertionError: expected ‘POST’ to contain one of [ ‘GET’, ‘HEAD’ ]
What must be done to make the second condition (if) to work?
Assertions ideally should be within pm.test()'s, so that the script execution does not stop. In your case, since the current request’s HTTP method is POST, your pm.expect() statement fails with the error message you get, which is the correct behaviour.
Using lodash’s includes method, you can accomplish what you are after, as follows:
if (_.includes(['GET', 'HEAD'], pm.request.method)) {
pm.test("Verify that the GET and HEAD methods are not deactivated", function () {
pm.expect(pm.response.code).to.not.eql(405);
});
}
Works perfect! So Postman allows you to use syntax from both the Chai and Lodash libraries? Are there other resources where I can get other references to operations/statements?
On a side note, you can use the includes() method for arrays.
if (['GET', 'HEAD'].includes(pm.request.method)) {
pm.test("Verify that the GET and HEAD methods are not deactivated", function () {
pm.expect(pm.response.code).to.not.eql(405);
});
}