Created
August 30, 2024 08:19
-
-
Save johannschopplich/6d5d74cc5d1ff429192955bdfc0575cd to your computer and use it in GitHub Desktop.
unenv `createMock`, but optimized
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
const fn = function () {} | |
function createMock(name: string, overrides: Record<any, any> = {}): any { | |
fn.prototype.name = name | |
const props: Record<any, any> = {} | |
return new Proxy(fn, { | |
get(_target, prop) { | |
if (prop === 'caller') { | |
return null | |
} | |
if (prop === '__createMock__') { | |
return createMock | |
} | |
if (prop === '__unenv__') { | |
return true | |
} | |
if (prop in overrides) { | |
return overrides[prop as keyof typeof overrides] | |
} | |
return ( | |
props[prop as keyof typeof props] ||= createMock(`${name}.${prop.toString()}`) | |
) | |
}, | |
apply(_target, _this, _args) { | |
return createMock(`${name}()`) | |
}, | |
construct(_target, _args, _newT) { | |
return createMock(`[${name}]`) as object | |
}, | |
}) | |
} | |
export default createMock('mock') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment