apiWatch.spec.ts 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122
  1. import {
  2. type ComponentInternalInstance,
  3. type ComponentPublicInstance,
  4. computed,
  5. defineComponent,
  6. getCurrentInstance,
  7. nextTick,
  8. onErrorCaptured,
  9. onWatcherCleanup,
  10. reactive,
  11. ref,
  12. watch,
  13. watchEffect,
  14. } from '../src/index'
  15. import {
  16. type TestElement,
  17. createApp,
  18. h,
  19. nodeOps,
  20. onMounted,
  21. render,
  22. serializeInner,
  23. watchPostEffect,
  24. watchSyncEffect,
  25. } from '@vue/runtime-test'
  26. import {
  27. type DebuggerEvent,
  28. type EffectScope,
  29. ITERATE_KEY,
  30. ReactiveEffect,
  31. type Ref,
  32. type ShallowRef,
  33. TrackOpTypes,
  34. TriggerOpTypes,
  35. effectScope,
  36. onScopeDispose,
  37. shallowReactive,
  38. shallowRef,
  39. toRef,
  40. triggerRef,
  41. } from '@vue/reactivity'
  42. import { renderToString } from '@vue/server-renderer'
  43. describe('api: watch', () => {
  44. it('effect', async () => {
  45. const state = reactive({ count: 0 })
  46. let dummy
  47. watchEffect(() => {
  48. dummy = state.count
  49. })
  50. expect(dummy).toBe(0)
  51. state.count++
  52. await nextTick()
  53. expect(dummy).toBe(1)
  54. })
  55. it('watching single source: getter', async () => {
  56. const state = reactive({ count: 0 })
  57. let dummy
  58. watch(
  59. () => state.count,
  60. (count, prevCount) => {
  61. dummy = [count, prevCount]
  62. // assert types
  63. count + 1
  64. if (prevCount) {
  65. prevCount + 1
  66. }
  67. },
  68. )
  69. state.count++
  70. await nextTick()
  71. expect(dummy).toMatchObject([1, 0])
  72. })
  73. it('watching single source: ref', async () => {
  74. const count = ref(0)
  75. let dummy
  76. watch(count, (count, prevCount) => {
  77. dummy = [count, prevCount]
  78. // assert types
  79. count + 1
  80. if (prevCount) {
  81. prevCount + 1
  82. }
  83. })
  84. count.value++
  85. await nextTick()
  86. expect(dummy).toMatchObject([1, 0])
  87. })
  88. it('watching single source: array', async () => {
  89. const array = reactive([] as number[])
  90. const spy = vi.fn()
  91. watch(array, spy)
  92. array.push(1)
  93. await nextTick()
  94. expect(spy).toBeCalledTimes(1)
  95. expect(spy).toBeCalledWith([1], [1], expect.anything())
  96. })
  97. it('should not call functions inside a reactive source array', () => {
  98. const spy1 = vi.fn()
  99. const array = reactive([spy1])
  100. const spy2 = vi.fn()
  101. watch(array, spy2, { immediate: true })
  102. expect(spy1).toBeCalledTimes(0)
  103. expect(spy2).toBeCalledWith([spy1], undefined, expect.anything())
  104. })
  105. it('should not unwrap refs in a reactive source array', async () => {
  106. const val = ref({ foo: 1 })
  107. const array = reactive([val])
  108. const spy = vi.fn()
  109. watch(array, spy, { immediate: true })
  110. expect(spy).toBeCalledTimes(1)
  111. expect(spy).toBeCalledWith([val], undefined, expect.anything())
  112. // deep by default
  113. val.value.foo++
  114. await nextTick()
  115. expect(spy).toBeCalledTimes(2)
  116. expect(spy).toBeCalledWith([val], [val], expect.anything())
  117. })
  118. it('should not fire if watched getter result did not change', async () => {
  119. const spy = vi.fn()
  120. const n = ref(0)
  121. watch(() => n.value % 2, spy)
  122. n.value++
  123. await nextTick()
  124. expect(spy).toBeCalledTimes(1)
  125. n.value += 2
  126. await nextTick()
  127. // should not be called again because getter result did not change
  128. expect(spy).toBeCalledTimes(1)
  129. })
  130. it('watching single source: computed ref', async () => {
  131. const count = ref(0)
  132. const plus = computed(() => count.value + 1)
  133. let dummy
  134. watch(plus, (count, prevCount) => {
  135. dummy = [count, prevCount]
  136. // assert types
  137. count + 1
  138. if (prevCount) {
  139. prevCount + 1
  140. }
  141. })
  142. count.value++
  143. await nextTick()
  144. expect(dummy).toMatchObject([2, 1])
  145. })
  146. it('watching primitive with deep: true', async () => {
  147. const count = ref(0)
  148. let dummy
  149. watch(
  150. count,
  151. (c, prevCount) => {
  152. dummy = [c, prevCount]
  153. },
  154. {
  155. deep: true,
  156. },
  157. )
  158. count.value++
  159. await nextTick()
  160. expect(dummy).toMatchObject([1, 0])
  161. })
  162. it('directly watching reactive object (with automatic deep: true)', async () => {
  163. const src = reactive({
  164. count: 0,
  165. })
  166. let dummy
  167. watch(src, ({ count }) => {
  168. dummy = count
  169. })
  170. src.count++
  171. await nextTick()
  172. expect(dummy).toBe(1)
  173. })
  174. it('directly watching reactive object with explicit deep: false', async () => {
  175. const src = reactive({
  176. state: {
  177. count: 0,
  178. },
  179. })
  180. let dummy
  181. watch(
  182. src,
  183. ({ state }) => {
  184. dummy = state?.count
  185. },
  186. {
  187. deep: false,
  188. },
  189. )
  190. // nested should not trigger
  191. src.state.count++
  192. await nextTick()
  193. expect(dummy).toBe(undefined)
  194. // root level should trigger
  195. src.state = { count: 1 }
  196. await nextTick()
  197. expect(dummy).toBe(1)
  198. })
  199. it('directly watching reactive array with explicit deep: false', async () => {
  200. const val = ref(1)
  201. const array: any[] = reactive([val])
  202. const spy = vi.fn()
  203. watch(array, spy, { immediate: true, deep: false })
  204. expect(spy).toBeCalledTimes(1)
  205. expect(spy).toBeCalledWith([val], undefined, expect.anything())
  206. val.value++
  207. await nextTick()
  208. expect(spy).toBeCalledTimes(1)
  209. array[1] = 2
  210. await nextTick()
  211. expect(spy).toBeCalledTimes(2)
  212. expect(spy).toBeCalledWith([val, 2], [val, 2], expect.anything())
  213. })
  214. // #9916
  215. it('watching shallow reactive array with deep: false', async () => {
  216. class foo {
  217. prop1: ShallowRef<string> = shallowRef('')
  218. prop2: string = ''
  219. }
  220. const obj1 = new foo()
  221. const obj2 = new foo()
  222. const collection = shallowReactive([obj1, obj2])
  223. const cb = vi.fn()
  224. watch(collection, cb, { deep: false })
  225. collection[0].prop1.value = 'foo'
  226. await nextTick()
  227. // should not trigger
  228. expect(cb).toBeCalledTimes(0)
  229. collection.push(new foo())
  230. await nextTick()
  231. // should trigger on array self mutation
  232. expect(cb).toBeCalledTimes(1)
  233. })
  234. it('should still respect deep: true on shallowReactive source', async () => {
  235. const obj = reactive({ a: 1 })
  236. const arr = shallowReactive([obj])
  237. let dummy
  238. watch(
  239. arr,
  240. () => {
  241. dummy = arr[0].a
  242. },
  243. { deep: true },
  244. )
  245. obj.a++
  246. await nextTick()
  247. expect(dummy).toBe(2)
  248. })
  249. it('watching multiple sources', async () => {
  250. const state = reactive({ count: 1 })
  251. const count = ref(1)
  252. const plus = computed(() => count.value + 1)
  253. let dummy
  254. watch([() => state.count, count, plus], (vals, oldVals) => {
  255. dummy = [vals, oldVals]
  256. // assert types
  257. vals.concat(1)
  258. oldVals.concat(1)
  259. })
  260. state.count++
  261. count.value++
  262. await nextTick()
  263. expect(dummy).toMatchObject([
  264. [2, 2, 3],
  265. [1, 1, 2],
  266. ])
  267. })
  268. it('watching multiple sources: undefined initial values and immediate: true', async () => {
  269. const a = ref()
  270. const b = ref()
  271. let called = false
  272. watch(
  273. [a, b],
  274. ([newA, newB], [oldA, oldB]) => {
  275. called = true
  276. expect([newA, newB]).toMatchObject([undefined, undefined])
  277. expect([oldA, oldB]).toMatchObject([undefined, undefined])
  278. },
  279. { immediate: true },
  280. )
  281. await nextTick()
  282. expect(called).toBe(true)
  283. })
  284. it('watching multiple sources: readonly array', async () => {
  285. const state = reactive({ count: 1 })
  286. const status = ref(false)
  287. let dummy
  288. watch([() => state.count, status] as const, (vals, oldVals) => {
  289. dummy = [vals, oldVals]
  290. const [count] = vals
  291. const [, oldStatus] = oldVals
  292. // assert types
  293. count + 1
  294. oldStatus === true
  295. })
  296. state.count++
  297. status.value = true
  298. await nextTick()
  299. expect(dummy).toMatchObject([
  300. [2, true],
  301. [1, false],
  302. ])
  303. })
  304. it('watching multiple sources: reactive object (with automatic deep: true)', async () => {
  305. const src = reactive({ count: 0 })
  306. let dummy
  307. watch([src], ([state]) => {
  308. dummy = state
  309. // assert types
  310. state.count === 1
  311. })
  312. src.count++
  313. await nextTick()
  314. expect(dummy).toMatchObject({ count: 1 })
  315. })
  316. it('warn invalid watch source', () => {
  317. // @ts-expect-error
  318. watch(1, () => {})
  319. expect(`Invalid watch source`).toHaveBeenWarned()
  320. })
  321. it('warn invalid watch source: multiple sources', () => {
  322. watch([1], () => {})
  323. expect(`Invalid watch source`).toHaveBeenWarned()
  324. })
  325. it('stopping the watcher (effect)', async () => {
  326. const state = reactive({ count: 0 })
  327. let dummy
  328. const stop = watchEffect(() => {
  329. dummy = state.count
  330. })
  331. expect(dummy).toBe(0)
  332. stop()
  333. state.count++
  334. await nextTick()
  335. // should not update
  336. expect(dummy).toBe(0)
  337. })
  338. it('stopping the watcher (SSR)', async () => {
  339. let dummy = 0
  340. const count = ref<number>(1)
  341. const captureValue = (value: number) => {
  342. dummy = value
  343. }
  344. const watchCallback = vi.fn(newValue => {
  345. captureValue(newValue)
  346. })
  347. const Comp = defineComponent({
  348. created() {
  349. const getter = () => this.count
  350. captureValue(getter()) // sets dummy to 1
  351. const stop = this.$watch(getter, watchCallback)
  352. stop()
  353. this.count = 2 // shouldn't trigger side effect
  354. },
  355. render() {
  356. return h('div', this.count)
  357. },
  358. setup() {
  359. return { count }
  360. },
  361. })
  362. let html
  363. html = await renderToString(h(Comp))
  364. // should not throw here
  365. expect(html).toBe(`<div>2</div>`)
  366. expect(watchCallback).not.toHaveBeenCalled()
  367. expect(dummy).toBe(1)
  368. await nextTick()
  369. count.value = 3 // shouldn't trigger side effect
  370. await nextTick()
  371. expect(watchCallback).not.toHaveBeenCalled()
  372. expect(dummy).toBe(1)
  373. })
  374. it('stopping the watcher (with source)', async () => {
  375. const state = reactive({ count: 0 })
  376. let dummy
  377. const stop = watch(
  378. () => state.count,
  379. count => {
  380. dummy = count
  381. },
  382. )
  383. state.count++
  384. await nextTick()
  385. expect(dummy).toBe(1)
  386. stop()
  387. state.count++
  388. await nextTick()
  389. // should not update
  390. expect(dummy).toBe(1)
  391. })
  392. it('cleanup registration (effect)', async () => {
  393. const state = reactive({ count: 0 })
  394. const cleanup = vi.fn()
  395. let dummy
  396. const stop = watchEffect(onCleanup => {
  397. onCleanup(cleanup)
  398. dummy = state.count
  399. })
  400. expect(dummy).toBe(0)
  401. state.count++
  402. await nextTick()
  403. expect(cleanup).toHaveBeenCalledTimes(1)
  404. expect(dummy).toBe(1)
  405. stop()
  406. expect(cleanup).toHaveBeenCalledTimes(2)
  407. })
  408. it('cleanup registration (with source)', async () => {
  409. const count = ref(0)
  410. const cleanup = vi.fn()
  411. let dummy
  412. const stop = watch(count, (count, prevCount, onCleanup) => {
  413. onCleanup(cleanup)
  414. dummy = count
  415. })
  416. count.value++
  417. await nextTick()
  418. expect(cleanup).toHaveBeenCalledTimes(0)
  419. expect(dummy).toBe(1)
  420. count.value++
  421. await nextTick()
  422. expect(cleanup).toHaveBeenCalledTimes(1)
  423. expect(dummy).toBe(2)
  424. stop()
  425. expect(cleanup).toHaveBeenCalledTimes(2)
  426. })
  427. it('onWatcherCleanup', async () => {
  428. const count = ref(0)
  429. const cleanupEffect = vi.fn()
  430. const cleanupWatch = vi.fn()
  431. const stopEffect = watchEffect(() => {
  432. onWatcherCleanup(cleanupEffect)
  433. count.value
  434. })
  435. const stopWatch = watch(count, () => {
  436. onWatcherCleanup(cleanupWatch)
  437. })
  438. count.value++
  439. await nextTick()
  440. expect(cleanupEffect).toHaveBeenCalledTimes(1)
  441. expect(cleanupWatch).toHaveBeenCalledTimes(0)
  442. count.value++
  443. await nextTick()
  444. expect(cleanupEffect).toHaveBeenCalledTimes(2)
  445. expect(cleanupWatch).toHaveBeenCalledTimes(1)
  446. stopEffect()
  447. expect(cleanupEffect).toHaveBeenCalledTimes(3)
  448. stopWatch()
  449. expect(cleanupWatch).toHaveBeenCalledTimes(2)
  450. })
  451. it('nested calls to baseWatch and onWatcherCleanup', async () => {
  452. let calls: string[] = []
  453. let source: Ref<number>
  454. let copyist: Ref<number>
  455. const scope = effectScope()
  456. scope.run(() => {
  457. source = ref(0)
  458. copyist = ref(0)
  459. // sync flush
  460. watchEffect(
  461. () => {
  462. const current = (copyist.value = source.value)
  463. onWatcherCleanup(() => calls.push(`sync ${current}`))
  464. },
  465. { flush: 'sync' },
  466. )
  467. // post flush
  468. watchEffect(
  469. () => {
  470. const current = copyist.value
  471. onWatcherCleanup(() => calls.push(`post ${current}`))
  472. },
  473. { flush: 'post' },
  474. )
  475. })
  476. await nextTick()
  477. expect(calls).toEqual([])
  478. scope.run(() => source.value++)
  479. expect(calls).toEqual(['sync 0'])
  480. await nextTick()
  481. expect(calls).toEqual(['sync 0', 'post 0'])
  482. calls.length = 0
  483. scope.run(() => source.value++)
  484. expect(calls).toEqual(['sync 1'])
  485. await nextTick()
  486. expect(calls).toEqual(['sync 1', 'post 1'])
  487. calls.length = 0
  488. scope.stop()
  489. expect(calls).toEqual(['sync 2', 'post 2'])
  490. })
  491. it('flush timing: pre (default)', async () => {
  492. const count = ref(0)
  493. const count2 = ref(0)
  494. let callCount = 0
  495. let result1
  496. let result2
  497. const assertion = vi.fn((count, count2Value) => {
  498. callCount++
  499. // on mount, the watcher callback should be called before DOM render
  500. // on update, should be called before the count is updated
  501. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  502. result1 = serializeInner(root) === expectedDOM
  503. // in a pre-flush callback, all state should have been updated
  504. const expectedState = callCount - 1
  505. result2 = count === expectedState && count2Value === expectedState
  506. })
  507. const Comp = {
  508. setup() {
  509. watchEffect(() => {
  510. assertion(count.value, count2.value)
  511. })
  512. return () => count.value
  513. },
  514. }
  515. const root = nodeOps.createElement('div')
  516. render(h(Comp), root)
  517. expect(assertion).toHaveBeenCalledTimes(1)
  518. expect(result1).toBe(true)
  519. expect(result2).toBe(true)
  520. count.value++
  521. count2.value++
  522. await nextTick()
  523. // two mutations should result in 1 callback execution
  524. expect(assertion).toHaveBeenCalledTimes(2)
  525. expect(result1).toBe(true)
  526. expect(result2).toBe(true)
  527. })
  528. it('flush timing: post', async () => {
  529. const count = ref(0)
  530. let result
  531. const assertion = vi.fn(count => {
  532. result = serializeInner(root) === `${count}`
  533. })
  534. const Comp = {
  535. setup() {
  536. watchEffect(
  537. () => {
  538. assertion(count.value)
  539. },
  540. { flush: 'post' },
  541. )
  542. return () => count.value
  543. },
  544. }
  545. const root = nodeOps.createElement('div')
  546. render(h(Comp), root)
  547. expect(assertion).toHaveBeenCalledTimes(1)
  548. expect(result).toBe(true)
  549. count.value++
  550. await nextTick()
  551. expect(assertion).toHaveBeenCalledTimes(2)
  552. expect(result).toBe(true)
  553. })
  554. it('watchPostEffect', async () => {
  555. const count = ref(0)
  556. let result
  557. const assertion = vi.fn(count => {
  558. result = serializeInner(root) === `${count}`
  559. })
  560. const Comp = {
  561. setup() {
  562. watchPostEffect(() => {
  563. assertion(count.value)
  564. })
  565. return () => count.value
  566. },
  567. }
  568. const root = nodeOps.createElement('div')
  569. render(h(Comp), root)
  570. expect(assertion).toHaveBeenCalledTimes(1)
  571. expect(result).toBe(true)
  572. count.value++
  573. await nextTick()
  574. expect(assertion).toHaveBeenCalledTimes(2)
  575. expect(result).toBe(true)
  576. })
  577. it('flush timing: sync', async () => {
  578. const count = ref(0)
  579. const count2 = ref(0)
  580. let callCount = 0
  581. let result1
  582. let result2
  583. const assertion = vi.fn(count => {
  584. callCount++
  585. // on mount, the watcher callback should be called before DOM render
  586. // on update, should be called before the count is updated
  587. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  588. result1 = serializeInner(root) === expectedDOM
  589. // in a sync callback, state mutation on the next line should not have
  590. // executed yet on the 2nd call, but will be on the 3rd call.
  591. const expectedState = callCount < 3 ? 0 : 1
  592. result2 = count2.value === expectedState
  593. })
  594. const Comp = {
  595. setup() {
  596. watchEffect(
  597. () => {
  598. assertion(count.value)
  599. },
  600. {
  601. flush: 'sync',
  602. },
  603. )
  604. return () => count.value
  605. },
  606. }
  607. const root = nodeOps.createElement('div')
  608. render(h(Comp), root)
  609. expect(assertion).toHaveBeenCalledTimes(1)
  610. expect(result1).toBe(true)
  611. expect(result2).toBe(true)
  612. count.value++
  613. count2.value++
  614. await nextTick()
  615. expect(assertion).toHaveBeenCalledTimes(3)
  616. expect(result1).toBe(true)
  617. expect(result2).toBe(true)
  618. })
  619. it('watchSyncEffect', async () => {
  620. const count = ref(0)
  621. const count2 = ref(0)
  622. let callCount = 0
  623. let result1
  624. let result2
  625. const assertion = vi.fn(count => {
  626. callCount++
  627. // on mount, the watcher callback should be called before DOM render
  628. // on update, should be called before the count is updated
  629. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  630. result1 = serializeInner(root) === expectedDOM
  631. // in a sync callback, state mutation on the next line should not have
  632. // executed yet on the 2nd call, but will be on the 3rd call.
  633. const expectedState = callCount < 3 ? 0 : 1
  634. result2 = count2.value === expectedState
  635. })
  636. const Comp = {
  637. setup() {
  638. watchSyncEffect(() => {
  639. assertion(count.value)
  640. })
  641. return () => count.value
  642. },
  643. }
  644. const root = nodeOps.createElement('div')
  645. render(h(Comp), root)
  646. expect(assertion).toHaveBeenCalledTimes(1)
  647. expect(result1).toBe(true)
  648. expect(result2).toBe(true)
  649. count.value++
  650. count2.value++
  651. await nextTick()
  652. expect(assertion).toHaveBeenCalledTimes(3)
  653. expect(result1).toBe(true)
  654. expect(result2).toBe(true)
  655. })
  656. it('should not fire on component unmount w/ flush: post', async () => {
  657. const toggle = ref(true)
  658. const cb = vi.fn()
  659. const Comp = {
  660. setup() {
  661. watch(toggle, cb, { flush: 'post' })
  662. },
  663. render() {},
  664. }
  665. const App = {
  666. render() {
  667. return toggle.value ? h(Comp) : null
  668. },
  669. }
  670. render(h(App), nodeOps.createElement('div'))
  671. expect(cb).not.toHaveBeenCalled()
  672. toggle.value = false
  673. await nextTick()
  674. expect(cb).not.toHaveBeenCalled()
  675. })
  676. // #2291
  677. it('should not fire on component unmount w/ flush: pre', async () => {
  678. const toggle = ref(true)
  679. const cb = vi.fn()
  680. const Comp = {
  681. setup() {
  682. watch(toggle, cb, { flush: 'pre' })
  683. },
  684. render() {},
  685. }
  686. const App = {
  687. render() {
  688. return toggle.value ? h(Comp) : null
  689. },
  690. }
  691. render(h(App), nodeOps.createElement('div'))
  692. expect(cb).not.toHaveBeenCalled()
  693. toggle.value = false
  694. await nextTick()
  695. expect(cb).not.toHaveBeenCalled()
  696. })
  697. // #7030
  698. it('should not fire on child component unmount w/ flush: pre', async () => {
  699. const visible = ref(true)
  700. const cb = vi.fn()
  701. const Parent = defineComponent({
  702. props: ['visible'],
  703. render() {
  704. return visible.value ? h(Comp) : null
  705. },
  706. })
  707. const Comp = {
  708. setup() {
  709. watch(visible, cb, { flush: 'pre' })
  710. },
  711. render() {},
  712. }
  713. const App = {
  714. render() {
  715. return h(Parent, {
  716. visible: visible.value,
  717. })
  718. },
  719. }
  720. render(h(App), nodeOps.createElement('div'))
  721. expect(cb).not.toHaveBeenCalled()
  722. visible.value = false
  723. await nextTick()
  724. expect(cb).not.toHaveBeenCalled()
  725. })
  726. // #7030
  727. it('flush: pre watcher in child component should not fire before parent update', async () => {
  728. const b = ref(0)
  729. const calls: string[] = []
  730. const Comp = {
  731. setup() {
  732. watch(
  733. () => b.value,
  734. val => {
  735. calls.push('watcher child')
  736. },
  737. { flush: 'pre' },
  738. )
  739. return () => {
  740. b.value
  741. calls.push('render child')
  742. }
  743. },
  744. }
  745. const Parent = {
  746. props: ['a'],
  747. setup() {
  748. watch(
  749. () => b.value,
  750. val => {
  751. calls.push('watcher parent')
  752. },
  753. { flush: 'pre' },
  754. )
  755. return () => {
  756. b.value
  757. calls.push('render parent')
  758. return h(Comp)
  759. }
  760. },
  761. }
  762. const App = {
  763. render() {
  764. return h(Parent, {
  765. a: b.value,
  766. })
  767. },
  768. }
  769. render(h(App), nodeOps.createElement('div'))
  770. expect(calls).toEqual(['render parent', 'render child'])
  771. b.value++
  772. await nextTick()
  773. expect(calls).toEqual([
  774. 'render parent',
  775. 'render child',
  776. 'watcher parent',
  777. 'render parent',
  778. 'watcher child',
  779. 'render child',
  780. ])
  781. })
  782. // #1763
  783. it('flush: pre watcher watching props should fire before child update', async () => {
  784. const a = ref(0)
  785. const b = ref(0)
  786. const c = ref(0)
  787. const calls: string[] = []
  788. const Comp = {
  789. props: ['a', 'b'],
  790. setup(props: any) {
  791. watch(
  792. () => props.a + props.b,
  793. () => {
  794. calls.push('watcher 1')
  795. c.value++
  796. },
  797. { flush: 'pre' },
  798. )
  799. // #1777 chained pre-watcher
  800. watch(
  801. c,
  802. () => {
  803. calls.push('watcher 2')
  804. },
  805. { flush: 'pre' },
  806. )
  807. return () => {
  808. c.value
  809. calls.push('render')
  810. }
  811. },
  812. }
  813. const App = {
  814. render() {
  815. return h(Comp, { a: a.value, b: b.value })
  816. },
  817. }
  818. render(h(App), nodeOps.createElement('div'))
  819. expect(calls).toEqual(['render'])
  820. // both props are updated
  821. // should trigger pre-flush watcher first and only once
  822. // then trigger child render
  823. a.value++
  824. b.value++
  825. await nextTick()
  826. expect(calls).toEqual(['render', 'watcher 1', 'watcher 2', 'render'])
  827. })
  828. // #5721
  829. it('flush: pre triggered in component setup should be buffered and called before mounted', () => {
  830. const count = ref(0)
  831. const calls: string[] = []
  832. const App = {
  833. render() {},
  834. setup() {
  835. watch(
  836. count,
  837. () => {
  838. calls.push('watch ' + count.value)
  839. },
  840. { flush: 'pre' },
  841. )
  842. onMounted(() => {
  843. calls.push('mounted')
  844. })
  845. // mutate multiple times
  846. count.value++
  847. count.value++
  848. count.value++
  849. },
  850. }
  851. render(h(App), nodeOps.createElement('div'))
  852. expect(calls).toMatchObject(['watch 3', 'mounted'])
  853. })
  854. // #1852
  855. it('flush: post watcher should fire after template refs updated', async () => {
  856. const toggle = ref(false)
  857. let dom: TestElement | null = null
  858. const App = {
  859. setup() {
  860. const domRef = ref<TestElement | null>(null)
  861. watch(
  862. toggle,
  863. () => {
  864. dom = domRef.value
  865. },
  866. { flush: 'post' },
  867. )
  868. return () => {
  869. return toggle.value ? h('p', { ref: domRef }) : null
  870. }
  871. },
  872. }
  873. render(h(App), nodeOps.createElement('div'))
  874. expect(dom).toBe(null)
  875. toggle.value = true
  876. await nextTick()
  877. expect(dom!.tag).toBe('p')
  878. })
  879. it('deep', async () => {
  880. const state = reactive({
  881. nested: {
  882. count: ref(0),
  883. },
  884. array: [1, 2, 3],
  885. map: new Map([
  886. ['a', 1],
  887. ['b', 2],
  888. ]),
  889. set: new Set([1, 2, 3]),
  890. })
  891. let dummy
  892. watch(
  893. () => state,
  894. state => {
  895. dummy = [
  896. state.nested.count,
  897. state.array[0],
  898. state.map.get('a'),
  899. state.set.has(1),
  900. ]
  901. },
  902. { deep: true },
  903. )
  904. state.nested.count++
  905. await nextTick()
  906. expect(dummy).toEqual([1, 1, 1, true])
  907. // nested array mutation
  908. state.array[0] = 2
  909. await nextTick()
  910. expect(dummy).toEqual([1, 2, 1, true])
  911. // nested map mutation
  912. state.map.set('a', 2)
  913. await nextTick()
  914. expect(dummy).toEqual([1, 2, 2, true])
  915. // nested set mutation
  916. state.set.delete(1)
  917. await nextTick()
  918. expect(dummy).toEqual([1, 2, 2, false])
  919. })
  920. it('watching deep ref', async () => {
  921. const count = ref(0)
  922. const double = computed(() => count.value * 2)
  923. const state = reactive([count, double])
  924. let dummy
  925. watch(
  926. () => state,
  927. state => {
  928. dummy = [state[0].value, state[1].value]
  929. },
  930. { deep: true },
  931. )
  932. count.value++
  933. await nextTick()
  934. expect(dummy).toEqual([1, 2])
  935. })
  936. it('deep with symbols', async () => {
  937. const symbol1 = Symbol()
  938. const symbol2 = Symbol()
  939. const symbol3 = Symbol()
  940. const symbol4 = Symbol()
  941. const raw: any = {
  942. [symbol1]: {
  943. [symbol2]: 1,
  944. },
  945. }
  946. Object.defineProperty(raw, symbol3, {
  947. writable: true,
  948. enumerable: false,
  949. value: 1,
  950. })
  951. const state = reactive(raw)
  952. const spy = vi.fn()
  953. watch(() => state, spy, { deep: true })
  954. await nextTick()
  955. expect(spy).toHaveBeenCalledTimes(0)
  956. state[symbol1][symbol2] = 2
  957. await nextTick()
  958. expect(spy).toHaveBeenCalledTimes(1)
  959. // Non-enumerable properties don't trigger deep watchers
  960. state[symbol3] = 3
  961. await nextTick()
  962. expect(spy).toHaveBeenCalledTimes(1)
  963. // Adding a new symbol property
  964. state[symbol4] = 1
  965. await nextTick()
  966. expect(spy).toHaveBeenCalledTimes(2)
  967. // Removing a symbol property
  968. delete state[symbol4]
  969. await nextTick()
  970. expect(spy).toHaveBeenCalledTimes(3)
  971. })
  972. it('immediate', async () => {
  973. const count = ref(0)
  974. const cb = vi.fn()
  975. watch(count, cb, { immediate: true })
  976. expect(cb).toHaveBeenCalledTimes(1)
  977. count.value++
  978. await nextTick()
  979. expect(cb).toHaveBeenCalledTimes(2)
  980. })
  981. it('immediate: triggers when initial value is null', async () => {
  982. const state = ref(null)
  983. const spy = vi.fn()
  984. watch(() => state.value, spy, { immediate: true })
  985. expect(spy).toHaveBeenCalled()
  986. })
  987. it('immediate: triggers when initial value is undefined', async () => {
  988. const state = ref()
  989. const spy = vi.fn()
  990. watch(() => state.value, spy, { immediate: true })
  991. expect(spy).toHaveBeenCalledWith(undefined, undefined, expect.any(Function))
  992. state.value = 3
  993. await nextTick()
  994. expect(spy).toHaveBeenCalledTimes(2)
  995. // testing if undefined can trigger the watcher
  996. state.value = undefined
  997. await nextTick()
  998. expect(spy).toHaveBeenCalledTimes(3)
  999. // it shouldn't trigger if the same value is set
  1000. state.value = undefined
  1001. await nextTick()
  1002. expect(spy).toHaveBeenCalledTimes(3)
  1003. })
  1004. it('warn immediate option when using effect', async () => {
  1005. const count = ref(0)
  1006. let dummy
  1007. watchEffect(
  1008. () => {
  1009. dummy = count.value
  1010. },
  1011. // @ts-expect-error
  1012. { immediate: false },
  1013. )
  1014. expect(dummy).toBe(0)
  1015. expect(`"immediate" option is only respected`).toHaveBeenWarned()
  1016. count.value++
  1017. await nextTick()
  1018. expect(dummy).toBe(1)
  1019. })
  1020. it('warn and not respect deep option when using effect', async () => {
  1021. const arr = ref([1, [2]])
  1022. const spy = vi.fn()
  1023. watchEffect(
  1024. () => {
  1025. spy()
  1026. return arr
  1027. },
  1028. // @ts-expect-error
  1029. { deep: true },
  1030. )
  1031. expect(spy).toHaveBeenCalledTimes(1)
  1032. ;(arr.value[1] as Array<number>)[0] = 3
  1033. await nextTick()
  1034. expect(spy).toHaveBeenCalledTimes(1)
  1035. expect(`"deep" option is only respected`).toHaveBeenWarned()
  1036. })
  1037. it('onTrack', async () => {
  1038. const events: DebuggerEvent[] = []
  1039. let dummy
  1040. const onTrack = vi.fn((e: DebuggerEvent) => {
  1041. events.push(e)
  1042. })
  1043. const obj = reactive({ foo: 1, bar: 2 })
  1044. watchEffect(
  1045. () => {
  1046. dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
  1047. },
  1048. { onTrack },
  1049. )
  1050. await nextTick()
  1051. expect(dummy).toEqual([1, true, ['foo', 'bar']])
  1052. expect(onTrack).toHaveBeenCalledTimes(3)
  1053. expect(events).toMatchObject([
  1054. {
  1055. target: obj,
  1056. type: TrackOpTypes.GET,
  1057. key: 'foo',
  1058. },
  1059. {
  1060. target: obj,
  1061. type: TrackOpTypes.HAS,
  1062. key: 'bar',
  1063. },
  1064. {
  1065. target: obj,
  1066. type: TrackOpTypes.ITERATE,
  1067. key: ITERATE_KEY,
  1068. },
  1069. ])
  1070. })
  1071. it('onTrigger', async () => {
  1072. const events: DebuggerEvent[] = []
  1073. let dummy
  1074. const onTrigger = vi.fn((e: DebuggerEvent) => {
  1075. events.push(e)
  1076. })
  1077. const obj = reactive<{ foo?: number }>({ foo: 1 })
  1078. watchEffect(
  1079. () => {
  1080. dummy = obj.foo
  1081. },
  1082. { onTrigger },
  1083. )
  1084. await nextTick()
  1085. expect(dummy).toBe(1)
  1086. obj.foo!++
  1087. await nextTick()
  1088. expect(dummy).toBe(2)
  1089. expect(onTrigger).toHaveBeenCalledTimes(1)
  1090. expect(events[0]).toMatchObject({
  1091. type: TriggerOpTypes.SET,
  1092. key: 'foo',
  1093. oldValue: 1,
  1094. newValue: 2,
  1095. })
  1096. delete obj.foo
  1097. await nextTick()
  1098. expect(dummy).toBeUndefined()
  1099. expect(onTrigger).toHaveBeenCalledTimes(2)
  1100. expect(events[1]).toMatchObject({
  1101. type: TriggerOpTypes.DELETE,
  1102. key: 'foo',
  1103. oldValue: 2,
  1104. })
  1105. })
  1106. it('should work sync', () => {
  1107. const v = ref(1)
  1108. let calls = 0
  1109. watch(
  1110. v,
  1111. () => {
  1112. ++calls
  1113. },
  1114. {
  1115. flush: 'sync',
  1116. },
  1117. )
  1118. expect(calls).toBe(0)
  1119. v.value++
  1120. expect(calls).toBe(1)
  1121. })
  1122. test('should force trigger on triggerRef when watching a shallow ref', async () => {
  1123. const v = shallowRef({ a: 1 })
  1124. let sideEffect = 0
  1125. watch(v, obj => {
  1126. sideEffect = obj.a
  1127. })
  1128. // oxlint-disable-next-line no-self-assign
  1129. v.value = v.value
  1130. await nextTick()
  1131. // should not trigger
  1132. expect(sideEffect).toBe(0)
  1133. v.value.a++
  1134. await nextTick()
  1135. // should not trigger
  1136. expect(sideEffect).toBe(0)
  1137. triggerRef(v)
  1138. await nextTick()
  1139. // should trigger now
  1140. expect(sideEffect).toBe(2)
  1141. })
  1142. test('should force trigger on triggerRef when watching multiple sources: shallow ref array', async () => {
  1143. const v = shallowRef([] as any)
  1144. const spy = vi.fn()
  1145. watch([v], () => {
  1146. spy()
  1147. })
  1148. v.value.push(1)
  1149. triggerRef(v)
  1150. await nextTick()
  1151. // should trigger now
  1152. expect(spy).toHaveBeenCalledTimes(1)
  1153. })
  1154. test('should force trigger on triggerRef with toRef from reactive', async () => {
  1155. const foo = reactive({ bar: 1 })
  1156. const bar = toRef(foo, 'bar')
  1157. const spy = vi.fn()
  1158. watchEffect(() => {
  1159. bar.value
  1160. spy()
  1161. })
  1162. expect(spy).toHaveBeenCalledTimes(1)
  1163. triggerRef(bar)
  1164. await nextTick()
  1165. // should trigger now
  1166. expect(spy).toHaveBeenCalledTimes(2)
  1167. })
  1168. // #2125
  1169. test('watchEffect should not recursively trigger itself', async () => {
  1170. const spy = vi.fn()
  1171. const price = ref(10)
  1172. const history = ref<number[]>([])
  1173. watchEffect(() => {
  1174. history.value.push(price.value)
  1175. spy()
  1176. })
  1177. await nextTick()
  1178. expect(spy).toHaveBeenCalledTimes(1)
  1179. })
  1180. // #2231
  1181. test('computed refs should not trigger watch if value has no change', async () => {
  1182. const spy = vi.fn()
  1183. const source = ref(0)
  1184. const price = computed(() => source.value === 0)
  1185. watch(price, spy)
  1186. source.value++
  1187. await nextTick()
  1188. source.value++
  1189. await nextTick()
  1190. expect(spy).toHaveBeenCalledTimes(1)
  1191. })
  1192. // https://github.com/vuejs/core/issues/2381
  1193. test('$watch should always register its effects with its own instance', async () => {
  1194. let instance: ComponentInternalInstance | null
  1195. let _show: Ref<boolean>
  1196. const Child = defineComponent({
  1197. render: () => h('div'),
  1198. mounted() {
  1199. instance = getCurrentInstance()
  1200. },
  1201. unmounted() {},
  1202. })
  1203. const Comp = defineComponent({
  1204. setup() {
  1205. const comp = ref<ComponentPublicInstance | undefined>()
  1206. const show = ref(true)
  1207. _show = show
  1208. return { comp, show }
  1209. },
  1210. render() {
  1211. return this.show
  1212. ? h(Child, {
  1213. ref: vm => void (this.comp = vm as ComponentPublicInstance),
  1214. })
  1215. : null
  1216. },
  1217. mounted() {
  1218. // this call runs while Comp is currentInstance, but
  1219. // the effect for this `$watch` should nonetheless be registered with Child
  1220. this.comp!.$watch(
  1221. () => this.show,
  1222. () => void 0,
  1223. )
  1224. },
  1225. })
  1226. render(h(Comp), nodeOps.createElement('div'))
  1227. expect(instance!).toBeDefined()
  1228. // includes the component's own render effect AND the watcher effect
  1229. expect(getEffectsCount(instance!.scope)).toBe(2)
  1230. _show!.value = false
  1231. await nextTick()
  1232. await nextTick()
  1233. expect(getEffectsCount(instance!.scope)).toBe(0)
  1234. })
  1235. test('this.$watch should pass `this.proxy` to watch source as the first argument ', () => {
  1236. let instance: any
  1237. const source = vi.fn()
  1238. const Comp = defineComponent({
  1239. render() {},
  1240. created(this: any) {
  1241. instance = this
  1242. this.$watch(source, function () {})
  1243. },
  1244. })
  1245. const root = nodeOps.createElement('div')
  1246. createApp(Comp).mount(root)
  1247. expect(instance).toBeDefined()
  1248. expect(source.mock.calls.some(args => args.includes(instance)))
  1249. })
  1250. test('should not leak `this.proxy` to setup()', () => {
  1251. const source = vi.fn()
  1252. const Comp = defineComponent({
  1253. render() {},
  1254. setup() {
  1255. watch(source, () => {})
  1256. },
  1257. })
  1258. const root = nodeOps.createElement('div')
  1259. createApp(Comp).mount(root)
  1260. // should not have any arguments
  1261. expect(source.mock.calls[0]).toMatchObject([])
  1262. })
  1263. // #2728
  1264. test('pre watcher callbacks should not track dependencies', async () => {
  1265. const a = ref(0)
  1266. const b = ref(0)
  1267. const updated = vi.fn()
  1268. const Child = defineComponent({
  1269. props: ['a'],
  1270. updated,
  1271. watch: {
  1272. a() {
  1273. b.value
  1274. },
  1275. },
  1276. render() {
  1277. return h('div', this.a)
  1278. },
  1279. })
  1280. const Parent = defineComponent({
  1281. render() {
  1282. return h(Child, { a: a.value })
  1283. },
  1284. })
  1285. const root = nodeOps.createElement('div')
  1286. createApp(Parent).mount(root)
  1287. a.value++
  1288. await nextTick()
  1289. expect(updated).toHaveBeenCalledTimes(1)
  1290. b.value++
  1291. await nextTick()
  1292. // should not track b as dependency of Child
  1293. expect(updated).toHaveBeenCalledTimes(1)
  1294. })
  1295. test('watching keypath', async () => {
  1296. const spy = vi.fn()
  1297. const Comp = defineComponent({
  1298. render() {},
  1299. data() {
  1300. return {
  1301. a: {
  1302. b: 1,
  1303. },
  1304. }
  1305. },
  1306. watch: {
  1307. 'a.b': spy,
  1308. },
  1309. created(this: any) {
  1310. this.$watch('a.b', spy)
  1311. },
  1312. mounted(this: any) {
  1313. this.a.b++
  1314. },
  1315. })
  1316. const root = nodeOps.createElement('div')
  1317. createApp(Comp).mount(root)
  1318. await nextTick()
  1319. expect(spy).toHaveBeenCalledTimes(2)
  1320. })
  1321. it('watching sources: ref<any[]>', async () => {
  1322. const foo = ref([1])
  1323. const spy = vi.fn()
  1324. watch(foo, () => {
  1325. spy()
  1326. })
  1327. foo.value = foo.value.slice()
  1328. await nextTick()
  1329. expect(spy).toBeCalledTimes(1)
  1330. })
  1331. it('watching multiple sources: computed', async () => {
  1332. let count = 0
  1333. const value = ref('1')
  1334. const plus = computed(() => !!value.value)
  1335. watch([plus], () => {
  1336. count++
  1337. })
  1338. value.value = '2'
  1339. await nextTick()
  1340. expect(plus.value).toBe(true)
  1341. expect(count).toBe(0)
  1342. })
  1343. // #4158
  1344. test('watch should not register in owner component if created inside detached scope', () => {
  1345. let instance: ComponentInternalInstance
  1346. const Comp = {
  1347. setup() {
  1348. instance = getCurrentInstance()!
  1349. effectScope(true).run(() => {
  1350. watch(
  1351. () => 1,
  1352. () => {},
  1353. )
  1354. })
  1355. return () => ''
  1356. },
  1357. }
  1358. const root = nodeOps.createElement('div')
  1359. createApp(Comp).mount(root)
  1360. // should not record watcher in detached scope and only the instance's
  1361. // own update effect
  1362. expect(getEffectsCount(instance!.scope)).toBe(1)
  1363. })
  1364. test('watchEffect should keep running if created in a detached scope', async () => {
  1365. const trigger = ref(0)
  1366. let countWE = 0
  1367. let countW = 0
  1368. const Comp = {
  1369. setup() {
  1370. effectScope(true).run(() => {
  1371. watchEffect(() => {
  1372. trigger.value
  1373. countWE++
  1374. })
  1375. watch(trigger, () => countW++)
  1376. })
  1377. return () => ''
  1378. },
  1379. }
  1380. const root = nodeOps.createElement('div')
  1381. render(h(Comp), root)
  1382. // only watchEffect as ran so far
  1383. expect(countWE).toBe(1)
  1384. expect(countW).toBe(0)
  1385. trigger.value++
  1386. await nextTick()
  1387. // both watchers run while component is mounted
  1388. expect(countWE).toBe(2)
  1389. expect(countW).toBe(1)
  1390. render(null, root) // unmount
  1391. await nextTick()
  1392. trigger.value++
  1393. await nextTick()
  1394. // both watchers run again event though component has been unmounted
  1395. expect(countWE).toBe(3)
  1396. expect(countW).toBe(2)
  1397. })
  1398. const options = [
  1399. { name: 'only trigger once watch' },
  1400. {
  1401. deep: true,
  1402. name: 'only trigger once watch with deep',
  1403. },
  1404. {
  1405. flush: 'sync',
  1406. name: 'only trigger once watch with flush: sync',
  1407. },
  1408. {
  1409. flush: 'pre',
  1410. name: 'only trigger once watch with flush: pre',
  1411. },
  1412. {
  1413. immediate: true,
  1414. name: 'only trigger once watch with immediate',
  1415. },
  1416. ] as const
  1417. test.each(options)('$name', async option => {
  1418. const count = ref(0)
  1419. const cb = vi.fn()
  1420. watch(count, cb, { once: true, ...option })
  1421. count.value++
  1422. await nextTick()
  1423. expect(count.value).toBe(1)
  1424. expect(cb).toHaveBeenCalledTimes(1)
  1425. count.value++
  1426. await nextTick()
  1427. expect(count.value).toBe(2)
  1428. expect(cb).toHaveBeenCalledTimes(1)
  1429. })
  1430. // #5151
  1431. test('OnCleanup also needs to be cleaned,', async () => {
  1432. const spy1 = vi.fn()
  1433. const spy2 = vi.fn()
  1434. const num = ref(0)
  1435. watch(num, (value, oldValue, onCleanup) => {
  1436. if (value > 1) {
  1437. return
  1438. }
  1439. spy1()
  1440. onCleanup(() => {
  1441. // OnCleanup also needs to be cleaned
  1442. spy2()
  1443. })
  1444. })
  1445. num.value++
  1446. await nextTick()
  1447. expect(spy1).toHaveBeenCalledTimes(1)
  1448. expect(spy2).toHaveBeenCalledTimes(0)
  1449. num.value++
  1450. await nextTick()
  1451. expect(spy1).toHaveBeenCalledTimes(1)
  1452. expect(spy2).toHaveBeenCalledTimes(1)
  1453. num.value++
  1454. await nextTick()
  1455. // would not be called when value>1
  1456. expect(spy1).toHaveBeenCalledTimes(1)
  1457. expect(spy2).toHaveBeenCalledTimes(1)
  1458. })
  1459. it('watching reactive depth', async () => {
  1460. const state = reactive({
  1461. a: {
  1462. b: {
  1463. c: {
  1464. d: {
  1465. e: 1,
  1466. },
  1467. },
  1468. },
  1469. },
  1470. })
  1471. const cb = vi.fn()
  1472. watch(state, cb, { deep: 2 })
  1473. state.a.b = { c: { d: { e: 2 } } }
  1474. await nextTick()
  1475. expect(cb).toHaveBeenCalledTimes(1)
  1476. state.a.b.c = { d: { e: 3 } }
  1477. await nextTick()
  1478. expect(cb).toHaveBeenCalledTimes(1)
  1479. state.a.b = { c: { d: { e: 4 } } }
  1480. await nextTick()
  1481. expect(cb).toHaveBeenCalledTimes(2)
  1482. })
  1483. it('watching ref depth', async () => {
  1484. const state = ref({
  1485. a: {
  1486. b: 2,
  1487. },
  1488. })
  1489. const cb = vi.fn()
  1490. watch(state, cb, { deep: 1 })
  1491. state.value.a.b = 3
  1492. await nextTick()
  1493. expect(cb).toHaveBeenCalledTimes(0)
  1494. state.value.a = { b: 3 }
  1495. await nextTick()
  1496. expect(cb).toHaveBeenCalledTimes(1)
  1497. })
  1498. it('watching array depth', async () => {
  1499. const arr = ref([
  1500. {
  1501. a: {
  1502. b: 2,
  1503. },
  1504. },
  1505. {
  1506. a: {
  1507. b: 3,
  1508. },
  1509. },
  1510. ])
  1511. const cb = vi.fn()
  1512. watch(arr, cb, { deep: 2 })
  1513. arr.value[0].a.b = 3
  1514. await nextTick()
  1515. expect(cb).toHaveBeenCalledTimes(0)
  1516. arr.value[0].a = { b: 3 }
  1517. await nextTick()
  1518. expect(cb).toHaveBeenCalledTimes(1)
  1519. arr.value[1].a = { b: 4 }
  1520. await nextTick()
  1521. expect(cb).toHaveBeenCalledTimes(2)
  1522. arr.value.push({ a: { b: 5 } })
  1523. await nextTick()
  1524. expect(cb).toHaveBeenCalledTimes(3)
  1525. arr.value.pop()
  1526. await nextTick()
  1527. expect(cb).toHaveBeenCalledTimes(4)
  1528. })
  1529. test('watching the same object at different depths', async () => {
  1530. const arr1: any[] = reactive([[[{ foo: {} }]]])
  1531. const arr2 = arr1[0]
  1532. const arr3 = arr2[0]
  1533. const obj = arr3[0]
  1534. arr1.push(arr3)
  1535. const cb1 = vi.fn()
  1536. const cb2 = vi.fn()
  1537. const cb3 = vi.fn()
  1538. const cb4 = vi.fn()
  1539. watch(arr1, cb1, { deep: 1 })
  1540. watch(arr1, cb2, { deep: 2 })
  1541. watch(arr1, cb3, { deep: 3 })
  1542. watch(arr1, cb4, { deep: 4 })
  1543. await nextTick()
  1544. expect(cb1).toHaveBeenCalledTimes(0)
  1545. expect(cb2).toHaveBeenCalledTimes(0)
  1546. expect(cb3).toHaveBeenCalledTimes(0)
  1547. expect(cb4).toHaveBeenCalledTimes(0)
  1548. obj.foo = {}
  1549. await nextTick()
  1550. expect(cb1).toHaveBeenCalledTimes(0)
  1551. expect(cb2).toHaveBeenCalledTimes(0)
  1552. expect(cb3).toHaveBeenCalledTimes(1)
  1553. expect(cb4).toHaveBeenCalledTimes(1)
  1554. obj.foo.bar = 1
  1555. await nextTick()
  1556. expect(cb1).toHaveBeenCalledTimes(0)
  1557. expect(cb2).toHaveBeenCalledTimes(0)
  1558. expect(cb3).toHaveBeenCalledTimes(1)
  1559. expect(cb4).toHaveBeenCalledTimes(2)
  1560. arr3.push(obj.foo)
  1561. await nextTick()
  1562. expect(cb1).toHaveBeenCalledTimes(0)
  1563. expect(cb2).toHaveBeenCalledTimes(1)
  1564. expect(cb3).toHaveBeenCalledTimes(2)
  1565. expect(cb4).toHaveBeenCalledTimes(3)
  1566. obj.foo.bar = 2
  1567. await nextTick()
  1568. expect(cb1).toHaveBeenCalledTimes(0)
  1569. expect(cb2).toHaveBeenCalledTimes(1)
  1570. expect(cb3).toHaveBeenCalledTimes(3)
  1571. expect(cb4).toHaveBeenCalledTimes(4)
  1572. })
  1573. test('pause / resume', async () => {
  1574. const count = ref(0)
  1575. const cb = vi.fn()
  1576. const { pause, resume } = watch(count, cb)
  1577. count.value++
  1578. await nextTick()
  1579. expect(cb).toHaveBeenCalledTimes(1)
  1580. expect(cb).toHaveBeenLastCalledWith(1, 0, expect.any(Function))
  1581. pause()
  1582. count.value++
  1583. await nextTick()
  1584. expect(cb).toHaveBeenCalledTimes(1)
  1585. expect(cb).toHaveBeenLastCalledWith(1, 0, expect.any(Function))
  1586. resume()
  1587. count.value++
  1588. await nextTick()
  1589. expect(cb).toHaveBeenCalledTimes(2)
  1590. expect(cb).toHaveBeenLastCalledWith(3, 1, expect.any(Function))
  1591. count.value++
  1592. await nextTick()
  1593. expect(cb).toHaveBeenCalledTimes(3)
  1594. expect(cb).toHaveBeenLastCalledWith(4, 3, expect.any(Function))
  1595. pause()
  1596. count.value++
  1597. await nextTick()
  1598. expect(cb).toHaveBeenCalledTimes(3)
  1599. expect(cb).toHaveBeenLastCalledWith(4, 3, expect.any(Function))
  1600. resume()
  1601. await nextTick()
  1602. expect(cb).toHaveBeenCalledTimes(4)
  1603. expect(cb).toHaveBeenLastCalledWith(5, 4, expect.any(Function))
  1604. })
  1605. it('shallowReactive', async () => {
  1606. const state = shallowReactive({
  1607. msg: ref('hello'),
  1608. foo: {
  1609. a: ref(1),
  1610. b: 2,
  1611. },
  1612. bar: 'bar',
  1613. })
  1614. const spy = vi.fn()
  1615. watch(state, spy)
  1616. state.msg.value = 'hi'
  1617. await nextTick()
  1618. expect(spy).not.toHaveBeenCalled()
  1619. state.bar = 'bar2'
  1620. await nextTick()
  1621. expect(spy).toHaveBeenCalledTimes(1)
  1622. state.foo.a.value++
  1623. state.foo.b++
  1624. await nextTick()
  1625. expect(spy).toHaveBeenCalledTimes(1)
  1626. state.bar = 'bar3'
  1627. await nextTick()
  1628. expect(spy).toHaveBeenCalledTimes(2)
  1629. })
  1630. it('watching reactive with deep: false', async () => {
  1631. const state = reactive({
  1632. foo: {
  1633. a: 2,
  1634. },
  1635. bar: 'bar',
  1636. })
  1637. const spy = vi.fn()
  1638. watch(state, spy, { deep: false })
  1639. state.foo.a++
  1640. await nextTick()
  1641. expect(spy).toHaveBeenCalledTimes(0)
  1642. state.bar = 'bar2'
  1643. await nextTick()
  1644. expect(spy).toHaveBeenCalledTimes(1)
  1645. })
  1646. test("effect should be removed from scope's effects after it is stopped", () => {
  1647. const num = ref(0)
  1648. let unwatch: () => void
  1649. let instance: ComponentInternalInstance
  1650. const Comp = {
  1651. setup() {
  1652. instance = getCurrentInstance()!
  1653. unwatch = watch(num, () => {
  1654. console.log(num.value)
  1655. })
  1656. return () => null
  1657. },
  1658. }
  1659. const root = nodeOps.createElement('div')
  1660. createApp(Comp).mount(root)
  1661. expect(getEffectsCount(instance!.scope)).toBe(2)
  1662. unwatch!()
  1663. expect(getEffectsCount(instance!.scope)).toBe(1)
  1664. const scope = effectScope()
  1665. scope.run(() => {
  1666. unwatch = watch(num, () => {
  1667. console.log(num.value)
  1668. })
  1669. })
  1670. expect(getEffectsCount(scope)).toBe(1)
  1671. unwatch!()
  1672. expect(getEffectsCount(scope)).toBe(0)
  1673. scope.run(() => {
  1674. watch(num, () => {}, { once: true, immediate: true })
  1675. })
  1676. expect(getEffectsCount(scope)).toBe(0)
  1677. })
  1678. // simplified case of VueUse syncRef
  1679. test('sync watcher should not be batched', () => {
  1680. const a = ref(0)
  1681. const b = ref(0)
  1682. let pauseB = false
  1683. watch(
  1684. a,
  1685. () => {
  1686. pauseB = true
  1687. b.value = a.value + 1
  1688. pauseB = false
  1689. },
  1690. { flush: 'sync' },
  1691. )
  1692. watch(
  1693. b,
  1694. () => {
  1695. if (!pauseB) {
  1696. throw new Error('should not be called')
  1697. }
  1698. },
  1699. { flush: 'sync' },
  1700. )
  1701. a.value = 1
  1702. expect(b.value).toBe(2)
  1703. })
  1704. test('watchEffect should not fire on computed deps that did not change', async () => {
  1705. const a = ref(0)
  1706. const c = computed(() => a.value % 2)
  1707. const spy = vi.fn()
  1708. watchEffect(() => {
  1709. spy()
  1710. c.value
  1711. })
  1712. expect(spy).toHaveBeenCalledTimes(1)
  1713. a.value += 2
  1714. await nextTick()
  1715. expect(spy).toHaveBeenCalledTimes(1)
  1716. })
  1717. test('circular reference', async () => {
  1718. const obj = { a: 1 }
  1719. // @ts-expect-error
  1720. obj.b = obj
  1721. const foo = ref(obj)
  1722. const spy = vi.fn()
  1723. watch(foo, spy, { deep: true })
  1724. // @ts-expect-error
  1725. foo.value.b.a = 2
  1726. await nextTick()
  1727. expect(spy).toHaveBeenCalledTimes(1)
  1728. expect(foo.value.a).toBe(2)
  1729. })
  1730. test('watch immediate error in effect scope should be caught by onErrorCaptured', async () => {
  1731. const warn = vi.spyOn(console, 'warn')
  1732. warn.mockImplementation(() => {})
  1733. const ERROR_IN_SCOPE = 'ERROR_IN_SCOPE'
  1734. const ERROR_OUT_SCOPE = 'ERROR_OUT_SCOPE'
  1735. const errors = ref<string[]>([])
  1736. const Comp = {
  1737. setup() {
  1738. const trigger = ref(0)
  1739. effectScope(true).run(() => {
  1740. watch(
  1741. trigger,
  1742. () => {
  1743. throw new Error(ERROR_IN_SCOPE)
  1744. },
  1745. { immediate: true },
  1746. )
  1747. })
  1748. watchEffect(() => {
  1749. throw new Error(ERROR_OUT_SCOPE)
  1750. })
  1751. return () => ''
  1752. },
  1753. }
  1754. const root = nodeOps.createElement('div')
  1755. render(
  1756. h(
  1757. {
  1758. setup(_, { slots }) {
  1759. onErrorCaptured(e => {
  1760. errors.value.push(e.message)
  1761. return false
  1762. })
  1763. return () => h('div', slots.default && slots.default())
  1764. },
  1765. },
  1766. null,
  1767. () => [h(Comp)],
  1768. ),
  1769. root,
  1770. )
  1771. await nextTick()
  1772. // only watchEffect as ran so far
  1773. expect(errors.value).toHaveLength(2)
  1774. expect(errors.value[0]).toBe(ERROR_IN_SCOPE)
  1775. expect(errors.value[1]).toBe(ERROR_OUT_SCOPE)
  1776. warn.mockRestore()
  1777. })
  1778. test('should be executed correctly', () => {
  1779. const v = ref(1)
  1780. let foo = ''
  1781. watch(
  1782. v,
  1783. () => {
  1784. foo += '1'
  1785. },
  1786. {
  1787. flush: 'sync',
  1788. },
  1789. )
  1790. watch(
  1791. v,
  1792. () => {
  1793. foo += '2'
  1794. },
  1795. {
  1796. flush: 'sync',
  1797. },
  1798. )
  1799. expect(foo).toBe('')
  1800. v.value++
  1801. expect(foo).toBe('12')
  1802. })
  1803. // 12045
  1804. test('sync watcher should not break pre watchers', async () => {
  1805. const count1 = ref(0)
  1806. const count2 = ref(0)
  1807. watch(
  1808. count1,
  1809. () => {
  1810. count2.value++
  1811. },
  1812. { flush: 'sync' },
  1813. )
  1814. const spy1 = vi.fn()
  1815. watch([count1, count2], spy1)
  1816. const spy2 = vi.fn()
  1817. watch(count1, spy2)
  1818. count1.value++
  1819. await nextTick()
  1820. expect(spy1).toHaveBeenCalled()
  1821. expect(spy2).toHaveBeenCalled()
  1822. })
  1823. // #12631
  1824. test('this.$watch w/ onScopeDispose', () => {
  1825. const onCleanup = vi.fn()
  1826. const toggle = ref(true)
  1827. const Comp = defineComponent({
  1828. render() {},
  1829. created(this: any) {
  1830. this.$watch(
  1831. () => 1,
  1832. function () {},
  1833. )
  1834. onScopeDispose(onCleanup)
  1835. },
  1836. })
  1837. const App = defineComponent({
  1838. render() {
  1839. return toggle.value ? h(Comp) : null
  1840. },
  1841. })
  1842. const root = nodeOps.createElement('div')
  1843. createApp(App).mount(root)
  1844. expect(onCleanup).toBeCalledTimes(0)
  1845. })
  1846. })
  1847. function getEffectsCount(scope: EffectScope): number {
  1848. let n = 0
  1849. for (let dep = scope.deps; dep !== undefined; dep = dep.nextDep) {
  1850. if (dep.dep instanceof ReactiveEffect) {
  1851. n++
  1852. }
  1853. }
  1854. return n
  1855. }