javascript / expert
Snippet
Private Class Field Interception for Next.js Server Action Unit Tests
Leverages OOP private class fields combined with JavaScript Proxy dynamic traps to create isolated unit test containers for Next.js Server Action state validation.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class ServerActionState {#executionToken;constructor(token) {this.#executionToken = token;}executeAction(payload) {if (!this.#executionToken) {throw new Error('Invalid token');}return { success: true, payload };}}export function createActionTestContainer(token) {const instance = new ServerActionState(token);return new Proxy(instance, {get(target, prop, receiver) {if (prop === 'hasToken') {return Reflect.has(target, prop) || token !== null;}const val = Reflect.get(target, prop, receiver);return typeof val === 'function' ? val.bind(target) : val;}});}
nextjs
Breakdown
1
class ServerActionState {
Encapsulates server-side action context inside a domain class.
2
#executionToken;
Uses hard private fields to ensure strict encapsulation of sensitive tokens.
3
return new Proxy(instance, {
Wraps the instance in a Proxy to intercept property access during unit test verification.
4
const val = Reflect.get(target, prop, receiver);
Uses Reflect API to maintain correct context binding when invoking target methods.