Parsing serialized functions in pre-request or test scripts. Inconsistent behavior

Hi,

You have the following code in a pre-request script or test script:

const src = "function myFunction() {console.log('Hello, world!')}; myFunction()";
const func = new Function(src);
func();

Running this in NodeJS (v14.15.5 in my case), “Hello world” is the output. Running this as a script in Postman outputs nothing to the console. However, if we change console.log() to throw new Error() then the respective exception event is triggered and is visible as usual. How can we get the console message from within such a function to be put in the console in Postman?

Now, lets change the function a bit to include some native Postman method calls and execute it as a test script:

const src = "function myFunction() {pm.test('Status code is 200', () => {pm.expect(pm.response.code).to.eql(200)})}; myFunction()";
const func = new Function(src);
func();

Running this triggers an error: ReferenceError: pm is not defined. Changing the () operator to .apply(this) didn’t resolve the issue. Calling eval() and passing it the serialized function however worked. How can we use the new Function() constructor instead of eval() in this case? How can we properly pass the scope to a parsed function without using eval(), which runs in the current scope?

Thanks in advance for your tips and assistance.