javascript / expert
Snippet
Proxy-Based Invocation Spies for Server Action Integration Tests
Employs JavaScript ES6 Proxy traps (apply trap) and Reflect.apply to intercept function calls and capture call telemetry during server action testing.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
export function createActionSpy(targetFn) {const calls = [];const spy = new Proxy(targetFn, {apply(target, thisArg, argArray) {const callRecord = { args: argArray, timestamp: Date.now() };calls.push(callRecord);return Reflect.apply(target, thisArg, argArray);}});return { spy, calls };}
nextjs
Breakdown
1
const spy = new Proxy(targetFn, {
Creates an ES6 Proxy wrapping the target function to intercept standard runtime operations.
2
apply(target, thisArg, argArray) {
Trap method invoked whenever the proxied target function is directly called as a function.
3
return Reflect.apply(target, thisArg, argArray);
Forwards the function invocation to the original target using standard Reflection primitives.