deep-stub-object
v2.0.4
Published
Proxy-backed custom error message instead of `TypeError: x is undefined`
Downloads
7
Readme
deep-stub-object
Proxy-backed custom error message instead of TypeError: x is undefined
Getting started
$ npm i deep-stub-object
Reference
export type DeepPartial<T> = T extends Record<string, unknown>
? {
readonly [P in keyof T]?: DeepPartial<T[P]>
}
: T
export type DeepRequired<T> = T extends Record<string, unknown>
? {
readonly [P in keyof T]-?: DeepRequired<T[P]>
}
: T
type Func<P extends readonly any[] = readonly any[], R extends any = any> = (...args: P) => R
type Nested = Func | { readonly [prop: string]: Nested }
export function deepStub<T extends Nested>(
target: DeepPartial<T> | undefined,
message: (path: readonly string[]) => string
): DeepRequired<T>
Usage
import 'ts-jest'
import { deepStub, DeepPartial } from 'deep-stub-object'
type Obj = {
x: () => 1
y: { x: () => 'test' }
z: { y: { x: () => true } }
}
const deepStubObj = (obj?: DeepPartial<Obj>) => deepStub(obj, (path) => path.join('.'))
describe('index', () => {
test('deepStub - throw', () => {
const stub = deepStubObj()
expect(() => stub.x()).toThrowError('x')
expect(() => stub.y.x()).toThrowError('y.x')
expect(() => stub.z.y.x()).toThrowError('z.y.x')
})
test('deepStub - no throw', () => {
const stub = deepStubObj({ x: () => 1, z: { y: { x: () => true } } })
expect(stub.x()).toEqual(1)
expect(stub.z.y.x()).toEqual(true)
})
})