Comparing a method with an array using "contain.oneOf"

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?

Hey @satellite-geologis10 ,

You may want to look at the lodash library available within Postman’s Sandbox.

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);
    });
}
1 Like

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?

The details on the external libraries are here.

Using external libraries | Postman Learning Center

1 Like

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);
    });
}
1 Like

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