Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions packages/reactivity/__tests__/watch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,40 @@ describe('watch', () => {
expect(onError.mock.calls[1]).toMatchObject(['oops in once watch'])
})

test('once option stops after sync callback throw', () => {
const onError = vi.fn()
const call: WatchOptions['call'] = function call(fn, type, args) {
if (Array.isArray(fn)) {
fn.forEach(f => call(f, type, args))
return
}
try {
fn.apply(null, args)
} catch (e) {
onError(e, type)
}
}

const source = ref(0)
const cb = vi.fn(() => {
throw 'oops in once watch'
})

watch(source, cb, { call, once: true })

source.value++
expect(cb).toHaveBeenCalledTimes(1)
expect(onError.mock.calls).toMatchObject([
['oops in once watch', WatchErrorCodes.WATCH_CALLBACK],
])

source.value++
expect(cb).toHaveBeenCalledTimes(1)
expect(onError.mock.calls).toMatchObject([
['oops in once watch', WatchErrorCodes.WATCH_CALLBACK],
])
})

test('watch with onWatcherCleanup', async () => {
let dummy = 0
let source: Ref<number>
Expand Down
8 changes: 5 additions & 3 deletions packages/reactivity/src/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,11 @@ export function watch(
if (once && cb) {
const _cb = cb
cb = (...args) => {
const res = _cb(...args)
watchHandle()
return res
try {
return _cb(...args)
} finally {
watchHandle()
}
}
}

Expand Down