Skip to content

Instantly share code, notes, and snippets.

@zthxxx
Last active January 19, 2024 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zthxxx/c2ef41a3f948b58fc138b28febde73d0 to your computer and use it in GitHub Desktop.
Save zthxxx/c2ef41a3f948b58fc138b28febde73d0 to your computer and use it in GitHub Desktop.
/**
* Allows arbitrary level property access and callable,
* support mock with usage likes:
* ```
* faker = new FakeClass()
* faker.xxxx()
*
* faker()
*
* {...faker()}
*
* faker.xxx()
*
* faker[xxx].xxx()
* ```
*/
export const anyNestingMock = () => new Proxy(
/**
* make self callable with `[[Call]]` and `[[Construct]]` internal method
* by proxy target as a function object
* https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist
*/
function () {},
{
/** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/construct */
construct: () => anyNestingMock(),
/** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply */
apply: () => anyNestingMock(),
get: (target, prop) => {
if (prop === Symbol.toPrimitive) return () => ''
return anyNestingMock()
},
},
)
const instance1 = anyNestingMock()
const instance2 = anyNestingMock()
// unit test for the mocker of anyNestingMock
assert(instance1())
assert(new instance1())
assert({ ...instance1() })
assert(instance1.xxx())
assert({ ...instance1.xxx() })
assert(instance1[instance2].xxx())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment