1

I would like to create a proxy object that intercepts all property retrievals and function calls, and returns undefined.

Accomplishing the former is trivial:

const proxy = new Proxy({}, { get: () => undefined });
proxy.foo // undefined

In fact, I don't even need a proxy for this, an empty object ({}) will do the same. However, doing the same for function calls throws an error:

proxy.foo() // TypeError: proxy.foo is not a function

I could have the get trap return a function:

const proxy = new Proxy({}, { get: () => () => undefined });
proxy.foo() // undefined
proxy.foo // [Function]

But as you can see, it will return a function instead of undefined for my original property access case. Is it possible to accomplish what I want?

const proxy = ???;
proxy.foo; // undefined
proxy.foo(); // undefined

The end goal is to use this as a "catch-all" stub for testing.

UPDATE: Thanks to @Bergi for his answer. The following code accomplishes what I want:

const proxy = new Proxy(new Function, {
  get: (target, prop, receiver) => receiver,
});

console.log('proxy.foo', proxy.foo); // undefined
console.log('proxy.foo()', proxy.foo()); // undefined
console.log('proxy.foo.bar', proxy.foo.bar); // undefined
console.log('proxy.foo.bar()', proxy.foo.bar()); // undefined

2 Answers 2

1

No, this is not possible. A proxy does not intercept method calls, it can only intercept calls to the proxy itself (as in proxy()). A method call is just a property access followed by a function call to the property value. And it's impossible to have a value that is both undefined and a function.

To have a truly catch-all stub for testing, your proxy should return itself (or better, another proxy) for any access or call so that you can have arbitrary chains.

Sign up to request clarification or add additional context in comments.

Comments

0

Just to achieve only what you want, you can do this.

var obj = {
    foo: 1,
    bar: 2,
    fooFunc: () => {
        return "this is fooFunc";
    },
    barFunc: () => {
        return "this is barFunc";
    }
}

let Proxy = function (object) {

    for(var prop in object) {
        if(typeof object[prop] === 'function') {
            this[prop] = () => {
                return undefined;
            }
        }
        else {
            this[prop] = undefined;
        }
    }
}

let proxy = new Proxy(obj);

console.log(obj.foo);
console.log(proxy.foo);

console.log(obj.fooFunc());
console.log(proxy.fooFunc());

This isn't ideal to customize stubbing approaches but this works for your case I suppose.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.