Skip to content

Instantly share code, notes, and snippets.

@johannschopplich
Created August 30, 2024 08:19
Show Gist options
  • Save johannschopplich/6d5d74cc5d1ff429192955bdfc0575cd to your computer and use it in GitHub Desktop.
Save johannschopplich/6d5d74cc5d1ff429192955bdfc0575cd to your computer and use it in GitHub Desktop.
unenv `createMock`, but optimized
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