apiWatch.spec.ts 47 KB

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