Skip to content

Commit

Permalink
fix: isolated stub.builder
Browse files Browse the repository at this point in the history
  • Loading branch information
unional committed May 11, 2023
1 parent 30eb857 commit caa70e9
Showing 3 changed files with 33 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/serious-hats-press.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'type-plus': patch
---

Support isolated stub.builder use case.
25 changes: 21 additions & 4 deletions ts/testing/stub.builder.spec.ts
Original file line number Diff line number Diff line change
@@ -21,14 +21,31 @@ it('can add init object to builder', () => {
})

it('can add init function to builder', () => {
const s = stub.builder<{ a: number; b?: string }>(input => ({
...input,
a: (input?.a ?? 0) + 1 }))
const s = stub
.builder<{ a: number; b?: string }>(input => ({
...input,
a: (input?.a ?? 0) + 1
}))
.with(input => ({
...input,
b: (input?.b ?? '0') + '1' }))
b: (input?.b ?? '0') + '1'
}))
.create()
expect(s()).toEqual({ a: 1, b: '01' })
expect(s({ a: 1 })).toEqual({ a: 2, b: '01' })
expect(s({ a: 1 })).toEqual({ a: 2, b: '01' })
})

it('can be use to create multiple builders', () => {
const s = stub.builder<{ a: number; b: number; c: number }>({ a: 1 })
const s1 = s.with({ b: 2 })
const s2 = s.with({ b: 3 })
const b1 = s1.create()
const b2 = s2.create()

expect(b1({ c: 0 })).toEqual({ a: 1, b: 2, c: 0 })
expect(b1({ c: 1 })).toEqual({ a: 1, b: 2, c: 1 })

expect(b2({ c: 0 })).toEqual({ a: 1, b: 3, c: 0 })
expect(b2({ c: 1 })).toEqual({ a: 1, b: 3, c: 1 })
})
11 changes: 7 additions & 4 deletions ts/testing/stub.ts
Original file line number Diff line number Diff line change
@@ -38,7 +38,12 @@ function build<T>(init: RecursivePartial<T> | ((stub?: RecursivePartial<T>) => R
* ```
*/
function builder<T>(init: RecursivePartial<T> | ((stub?: RecursivePartial<T>) => RecursivePartial<T>)) {
const initializers = [init]
return builderInternal([init])
}

function builderInternal<T>(
initializers: Array<RecursivePartial<T> | ((stub?: RecursivePartial<T>) => RecursivePartial<T>)>
) {
const builder = {
/**
* Adds an init object or handler to the builder.
@@ -49,8 +54,7 @@ function builder<T>(init: RecursivePartial<T> | ((stub?: RecursivePartial<T>) =>
* @return {Builder<T>} The builder instance.
*/
with(init: RecursivePartial<T> | ((stub?: RecursivePartial<T>) => RecursivePartial<T>)) {
initializers.push(init)
return builder
return builderInternal([...initializers, init])
},
/**
* Creates the resulting stub function.
@@ -69,6 +73,5 @@ function builder<T>(init: RecursivePartial<T> | ((stub?: RecursivePartial<T>) =>
}
return builder
}

stub.build = build
stub.builder = builder

0 comments on commit caa70e9

Please sign in to comment.