deep-stub-object
TypeScript icon, indicating that this package has built-in type declarations

2.0.4 • Public • Published

deep-stub-object

npm build publish codecov Type Coverage Libraries.io dependency status for latest release Bundlephobia npm

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)
  })
})

Dependencies (0)

    Dev Dependencies (16)

    Package Sidebar

    Install

    npm i deep-stub-object

    Weekly Downloads

    0

    Version

    2.0.4

    License

    MIT

    Unpacked Size

    11.5 kB

    Total Files

    11

    Last publish

    Collaborators

    • iyegoroff