I have a Test that uses a Find function to pull out an object from an array of objects that matches a set of specific parameters. Example:
let object = response.items.find(x => {
x.name = A &&
x.size = B &&
x.type = C &&
x.price = D
}
);
The test works fine as-is. However, I use this Test with multiple environments. Some of them don’t return the JSON response with the exact same format. For example, some of them might leave out “x.price”, but include the rest of the key:values. This causes the test to abruptly fail.
Is it possible to include an IF statement within the find() function so that if I’m using a specific environment, it can include/exclude a search parameter?
@SKSG I am pretty sure the code that you shared doesn’t work since it has invalid javascript code.
And I am not quite sure you’re trying to do achieve with find?
I haven’t had luck putting the if statement inside the find function, since it’s going to return an object (forgot to add the return statement at the top line within the find function.) Since its looking for a number of matching values, I think it looks at the code within the ‘if’ statement as a command, rather than a value to compare to. So far it looks like this:
let object = response.items.find(x => {
return (x.name = A) &&
(x.size = B) &&
(x.type = C) &&
if (environment == "foo"){
(x.price = D)
}
}
);
I can’t run this properly though, since Postman throws a bunch of errors about including that ‘if’ statement. Any other ideas I can work with?
Hey @SKSG. Not sure if I understand the use case entirely but if you’re trying to change the keys to consider in a find operation based on some condition, you could do that by moving the condition out of the find block and based on that decide what all to consider.