Ensure that array in response contains variable value

Hello friends!
I’ve already broken my head and need assistance.

I have response:

[
    {
        "name": "documentName1",
        "documentId": 101
    },
    {
        "name": "documentName2",
        "documentId": 102
    },
    {
        "name": "documentName3",
        "documentId": 103
    }
]

documentId = 103 is added to environment variable {{documentId3}}.

So, I need to ensure that some of documentIds has the value from variable.

I’ve tried:

const schema = pm.response.json();
pm.test('Document is in response', function () {
	pm.expect(schema.find(obj => obj.documentId === (pm.environment.get("{{documentId3}}")))).to.exist;
});

pm.expect(schema.find(obj => obj.documentId === pm.environment.get("{{documentId3}}"))).to.exist;

pm.expect(schema.find(obj => obj.documentId === {{documentId3}})).to.exist;

pm.expect(schema.find(obj => obj.documentId === documentId3)).to.exist;

and other variations of writing the variable but I get “AssertionError: expected undefined to exist”.

How to write such function correctly?

Thank you in advance.

Decision is found:

const schema = pm.response.json();
const docId = pm.environment.replaceIn("{{documentId3}}");
pm.test('Document is in response', function () {
	pm.expect(schema.find(obj => obj.documentId == docId)).to.exist;
});

Perhaps not the most elegant but looks like working.

1 Like

What I normally do is define the find as its own variable first.

I can then add console logs to confirm its all working before the pm.expect assertion that usually just checks that its not undefined. (That’s its found something in the find). To exist is also fine.

I like your solution better for simple finds against a flat array so will probably use that in the future. For your example JSON, your method is clean and legible.

I’ll keep defining the variable if the JSON is a bit more complex or for searching for multiple elements. Mainly for troubleshooting purposes.