Last active
July 7, 2024 13:28
-
-
Save zthxxx/c2ef41a3f948b58fc138b28febde73d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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