Q28 of 40 · JavaScript
What is a JavaScript `Proxy`, and what can it intercept?
JavaScriptMidjavascriptproxyreflectmetaprogrammingmocking
Short answer
Short answer: A `Proxy` wraps an object and intercepts fundamental operations via handler traps: `get`, `set`, `has`, `deleteProperty`, `apply`, and more. Used for validation, logging, reactive state (Vue 3), auto-mocking in tests, and creating observable objects.
Detail
new Proxy(target, handler) creates a transparent wrapper that intercepts operations on the target object through named traps.
Common traps:
get(target, prop)— intercept property readsset(target, prop, value)— intercept property writes (return true to signal success)has(target, prop)— intercept theinoperatordeleteProperty(target, prop)— interceptdeleteapply(target, thisArg, args)— intercept function calls (when target is a function)construct(target, args)— interceptnew
Reflect: Used inside traps to call the default behaviour: return Reflect.get(target, prop, receiver). This ensures correct prototype chain handling.
Use cases in testing:
- Auto-mock: a Proxy can return a new function (or another Proxy) for any property access, creating lazy mocks that don't need upfront configuration.
- Validation: enforce that test fixtures only set allowed properties.
- Spy: record every property access or call during a test.
Vue 3 uses Proxy for its reactivity system; understanding Proxy helps when debugging Vue component tests.
// EXAMPLE
// Validation proxy — prevent unknown property writes
function createValidated(obj, allowedKeys) {
return new Proxy(obj, {
set(target, prop, value) {
if (!allowedKeys.includes(prop)) {
throw new TypeError(`Unknown property: ${prop}`);
}
target[prop] = value;
return true;
},
});
}
const user = createValidated({}, ["name", "email"]);
user.name = "Alice"; // ok
// user.typo = "oops"; // throws TypeError
// Auto-mock proxy for tests
function autoMock() {
return new Proxy({}, {
get(_, prop) {
return (...args) => {
console.log(`Called: ${prop}(${args})`);
return undefined;
};
},
});
}
const mock = autoMock();
mock.fetchUser(42); // logs "Called: fetchUser(42)"// WHAT INTERVIEWERS LOOK FOR
The trap-based interception model, common traps (get/set/apply), and the Reflect helper. Practical use cases — especially auto-mocking or validation in test contexts. Vue 3 reactivity knowledge is a bonus.
// COMMON PITFALL
Forgetting to return `true` from a `set` trap in strict mode — omitting it causes a TypeError: 'set' on proxy returned false.