Skip to content

Commit 25a974f

Browse files
authored
feat: "nextResult" doesn't override previous call (#38)
1 parent 6e06818 commit 25a974f

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

src/internal.ts

+8-7
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ let reset = (state: SpyInternalState) => {
1313
state.callCount = 0
1414
state.calls = []
1515
state.results = []
16+
state.next = []
1617
}
1718
let defineState = (spy: SpyInternal) => {
1819
define(spy, S, { value: { reset: () => reset(spy[S]) } })
@@ -43,7 +44,7 @@ interface SpyInternalState<A extends any[] = any[], R = any> {
4344
results: ResultFn<R>[]
4445
reset(): void
4546
impl: ((...args: A) => R) | undefined
46-
next: ResultFn<R> | null
47+
next: ResultFn<R>[]
4748
}
4849

4950
interface SpyInternalImplState<A extends any[] = any[], R = any>
@@ -80,10 +81,10 @@ export function createInternalSpy<A extends any[], R>(
8081
state.called = true
8182
state.callCount++
8283
state.calls.push(args)
83-
if (state.next) {
84-
let [type, result] = state.next
85-
state.results.push(state.next)
86-
state.next = null
84+
const next = state.next.shift()
85+
if (next) {
86+
state.results.push(next)
87+
const [type, result] = next
8788
if (type === 'ok') {
8889
return result
8990
}
@@ -150,11 +151,11 @@ export function populateSpy<A extends any[], R>(spy: SpyInternal<A, R>) {
150151
define(spy, n, { get: () => I[n], set: (v) => (I[n] = v as never) })
151152
)
152153
defineValue(spy, 'nextError', (error: any) => {
153-
I.next = ['error', error]
154+
I.next.push(['error', error])
154155
return I
155156
})
156157
defineValue(spy, 'nextResult', (result: R) => {
157-
I.next = ['ok', result]
158+
I.next.push(['ok', result])
158159
return I
159160
})
160161
}

test/index.test.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -697,11 +697,23 @@ test('does not await on non-promise values that contain .then', async () => {
697697

698698
test('.restore correctly restores primitive property', () => {
699699
const obj = {
700-
test: 42
700+
test: 42,
701701
}
702702
const spy = spyOn(obj, { getter: 'test' })
703703
spy.willCall(() => 10)
704704
expect(obj.test).toBe(10)
705705
spy.restore()
706706
expect(obj.test).toBe(42)
707707
})
708+
709+
test('next in a row', () => {
710+
const cb = spy()
711+
cb.nextResult(1)
712+
cb.nextResult(2)
713+
cb.nextResult(3)
714+
715+
expect(cb()).toBe(1)
716+
expect(cb()).toBe(2)
717+
expect(cb()).toBe(3)
718+
expect(cb()).toBe(undefined)
719+
})

0 commit comments

Comments
 (0)