apiWatch.spec.ts 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. import {
  2. type ComponentInternalInstance,
  3. type ComponentPublicInstance,
  4. computed,
  5. defineComponent,
  6. getCurrentInstance,
  7. nextTick,
  8. reactive,
  9. ref,
  10. watch,
  11. watchEffect,
  12. } from '../src/index'
  13. import {
  14. type TestElement,
  15. createApp,
  16. h,
  17. nodeOps,
  18. onMounted,
  19. render,
  20. serializeInner,
  21. watchPostEffect,
  22. watchSyncEffect,
  23. } from '@vue/runtime-test'
  24. import {
  25. type DebuggerEvent,
  26. ITERATE_KEY,
  27. type Ref,
  28. type ShallowRef,
  29. TrackOpTypes,
  30. TriggerOpTypes,
  31. effectScope,
  32. shallowReactive,
  33. shallowRef,
  34. toRef,
  35. triggerRef,
  36. } from '@vue/reactivity'
  37. describe('api: watch', () => {
  38. it('effect', async () => {
  39. const state = reactive({ count: 0 })
  40. let dummy
  41. watchEffect(() => {
  42. dummy = state.count
  43. })
  44. expect(dummy).toBe(0)
  45. state.count++
  46. await nextTick()
  47. expect(dummy).toBe(1)
  48. })
  49. it('watching single source: getter', async () => {
  50. const state = reactive({ count: 0 })
  51. let dummy
  52. watch(
  53. () => state.count,
  54. (count, prevCount) => {
  55. dummy = [count, prevCount]
  56. // assert types
  57. count + 1
  58. if (prevCount) {
  59. prevCount + 1
  60. }
  61. },
  62. )
  63. state.count++
  64. await nextTick()
  65. expect(dummy).toMatchObject([1, 0])
  66. })
  67. it('watching single source: ref', async () => {
  68. const count = ref(0)
  69. let dummy
  70. watch(count, (count, prevCount) => {
  71. dummy = [count, prevCount]
  72. // assert types
  73. count + 1
  74. if (prevCount) {
  75. prevCount + 1
  76. }
  77. })
  78. count.value++
  79. await nextTick()
  80. expect(dummy).toMatchObject([1, 0])
  81. })
  82. it('watching single source: array', async () => {
  83. const array = reactive([] as number[])
  84. const spy = vi.fn()
  85. watch(array, spy)
  86. array.push(1)
  87. await nextTick()
  88. expect(spy).toBeCalledTimes(1)
  89. expect(spy).toBeCalledWith([1], [1], expect.anything())
  90. })
  91. it('should not call functions inside a reactive source array', () => {
  92. const spy1 = vi.fn()
  93. const array = reactive([spy1])
  94. const spy2 = vi.fn()
  95. watch(array, spy2, { immediate: true })
  96. expect(spy1).toBeCalledTimes(0)
  97. expect(spy2).toBeCalledWith([spy1], undefined, expect.anything())
  98. })
  99. it('should not unwrap refs in a reactive source array', async () => {
  100. const val = ref({ foo: 1 })
  101. const array = reactive([val])
  102. const spy = vi.fn()
  103. watch(array, spy, { immediate: true })
  104. expect(spy).toBeCalledTimes(1)
  105. expect(spy).toBeCalledWith([val], undefined, expect.anything())
  106. // deep by default
  107. val.value.foo++
  108. await nextTick()
  109. expect(spy).toBeCalledTimes(2)
  110. expect(spy).toBeCalledWith([val], [val], expect.anything())
  111. })
  112. it('should not fire if watched getter result did not change', async () => {
  113. const spy = vi.fn()
  114. const n = ref(0)
  115. watch(() => n.value % 2, spy)
  116. n.value++
  117. await nextTick()
  118. expect(spy).toBeCalledTimes(1)
  119. n.value += 2
  120. await nextTick()
  121. // should not be called again because getter result did not change
  122. expect(spy).toBeCalledTimes(1)
  123. })
  124. it('watching single source: computed ref', async () => {
  125. const count = ref(0)
  126. const plus = computed(() => count.value + 1)
  127. let dummy
  128. watch(plus, (count, prevCount) => {
  129. dummy = [count, prevCount]
  130. // assert types
  131. count + 1
  132. if (prevCount) {
  133. prevCount + 1
  134. }
  135. })
  136. count.value++
  137. await nextTick()
  138. expect(dummy).toMatchObject([2, 1])
  139. })
  140. it('watching primitive with deep: true', async () => {
  141. const count = ref(0)
  142. let dummy
  143. watch(
  144. count,
  145. (c, prevCount) => {
  146. dummy = [c, prevCount]
  147. },
  148. {
  149. deep: true,
  150. },
  151. )
  152. count.value++
  153. await nextTick()
  154. expect(dummy).toMatchObject([1, 0])
  155. })
  156. it('directly watching reactive object (with automatic deep: true)', async () => {
  157. const src = reactive({
  158. count: 0,
  159. })
  160. let dummy
  161. watch(src, ({ count }) => {
  162. dummy = count
  163. })
  164. src.count++
  165. await nextTick()
  166. expect(dummy).toBe(1)
  167. })
  168. it('directly watching reactive object with explicit deep: false', async () => {
  169. const src = reactive({
  170. state: {
  171. count: 0,
  172. },
  173. })
  174. let dummy
  175. watch(
  176. src,
  177. ({ state }) => {
  178. dummy = state?.count
  179. },
  180. {
  181. deep: false,
  182. },
  183. )
  184. // nested should not trigger
  185. src.state.count++
  186. await nextTick()
  187. expect(dummy).toBe(undefined)
  188. // root level should trigger
  189. src.state = { count: 1 }
  190. await nextTick()
  191. expect(dummy).toBe(1)
  192. })
  193. it('directly watching reactive array with explicit deep: false', async () => {
  194. const val = ref(1)
  195. const array: any[] = reactive([val])
  196. const spy = vi.fn()
  197. watch(array, spy, { immediate: true, deep: false })
  198. expect(spy).toBeCalledTimes(1)
  199. expect(spy).toBeCalledWith([val], undefined, expect.anything())
  200. val.value++
  201. await nextTick()
  202. expect(spy).toBeCalledTimes(1)
  203. array[1] = 2
  204. await nextTick()
  205. expect(spy).toBeCalledTimes(2)
  206. expect(spy).toBeCalledWith([val, 2], [val, 2], expect.anything())
  207. })
  208. // #9916
  209. it('watching shallow reactive array with deep: false', async () => {
  210. class foo {
  211. prop1: ShallowRef<string> = shallowRef('')
  212. prop2: string = ''
  213. }
  214. const obj1 = new foo()
  215. const obj2 = new foo()
  216. const collection = shallowReactive([obj1, obj2])
  217. const cb = vi.fn()
  218. watch(collection, cb, { deep: false })
  219. collection[0].prop1.value = 'foo'
  220. await nextTick()
  221. // should not trigger
  222. expect(cb).toBeCalledTimes(0)
  223. collection.push(new foo())
  224. await nextTick()
  225. // should trigger on array self mutation
  226. expect(cb).toBeCalledTimes(1)
  227. })
  228. it('should still respect deep: true on shallowReactive source', async () => {
  229. const obj = reactive({ a: 1 })
  230. const arr = shallowReactive([obj])
  231. let dummy
  232. watch(
  233. arr,
  234. () => {
  235. dummy = arr[0].a
  236. },
  237. { deep: true },
  238. )
  239. obj.a++
  240. await nextTick()
  241. expect(dummy).toBe(2)
  242. })
  243. it('watching multiple sources', async () => {
  244. const state = reactive({ count: 1 })
  245. const count = ref(1)
  246. const plus = computed(() => count.value + 1)
  247. let dummy
  248. watch([() => state.count, count, plus], (vals, oldVals) => {
  249. dummy = [vals, oldVals]
  250. // assert types
  251. vals.concat(1)
  252. oldVals.concat(1)
  253. })
  254. state.count++
  255. count.value++
  256. await nextTick()
  257. expect(dummy).toMatchObject([
  258. [2, 2, 3],
  259. [1, 1, 2],
  260. ])
  261. })
  262. it('watching multiple sources: undefined initial values and immediate: true', async () => {
  263. const a = ref()
  264. const b = ref()
  265. let called = false
  266. watch(
  267. [a, b],
  268. ([newA, newB], [oldA, oldB]) => {
  269. called = true
  270. expect([newA, newB]).toMatchObject([undefined, undefined])
  271. expect([oldA, oldB]).toMatchObject([undefined, undefined])
  272. },
  273. { immediate: true },
  274. )
  275. await nextTick()
  276. expect(called).toBe(true)
  277. })
  278. it('watching multiple sources: readonly array', async () => {
  279. const state = reactive({ count: 1 })
  280. const status = ref(false)
  281. let dummy
  282. watch([() => state.count, status] as const, (vals, oldVals) => {
  283. dummy = [vals, oldVals]
  284. const [count] = vals
  285. const [, oldStatus] = oldVals
  286. // assert types
  287. count + 1
  288. oldStatus === true
  289. })
  290. state.count++
  291. status.value = true
  292. await nextTick()
  293. expect(dummy).toMatchObject([
  294. [2, true],
  295. [1, false],
  296. ])
  297. })
  298. it('watching multiple sources: reactive object (with automatic deep: true)', async () => {
  299. const src = reactive({ count: 0 })
  300. let dummy
  301. watch([src], ([state]) => {
  302. dummy = state
  303. // assert types
  304. state.count === 1
  305. })
  306. src.count++
  307. await nextTick()
  308. expect(dummy).toMatchObject({ count: 1 })
  309. })
  310. it('warn invalid watch source', () => {
  311. // @ts-expect-error
  312. watch(1, () => {})
  313. expect(`Invalid watch source`).toHaveBeenWarned()
  314. })
  315. it('warn invalid watch source: multiple sources', () => {
  316. watch([1], () => {})
  317. expect(`Invalid watch source`).toHaveBeenWarned()
  318. })
  319. it('stopping the watcher (effect)', async () => {
  320. const state = reactive({ count: 0 })
  321. let dummy
  322. const stop = watchEffect(() => {
  323. dummy = state.count
  324. })
  325. expect(dummy).toBe(0)
  326. stop()
  327. state.count++
  328. await nextTick()
  329. // should not update
  330. expect(dummy).toBe(0)
  331. })
  332. it('stopping the watcher (with source)', async () => {
  333. const state = reactive({ count: 0 })
  334. let dummy
  335. const stop = watch(
  336. () => state.count,
  337. count => {
  338. dummy = count
  339. },
  340. )
  341. state.count++
  342. await nextTick()
  343. expect(dummy).toBe(1)
  344. stop()
  345. state.count++
  346. await nextTick()
  347. // should not update
  348. expect(dummy).toBe(1)
  349. })
  350. it('cleanup registration (effect)', async () => {
  351. const state = reactive({ count: 0 })
  352. const cleanup = vi.fn()
  353. let dummy
  354. const stop = watchEffect(onCleanup => {
  355. onCleanup(cleanup)
  356. dummy = state.count
  357. })
  358. expect(dummy).toBe(0)
  359. state.count++
  360. await nextTick()
  361. expect(cleanup).toHaveBeenCalledTimes(1)
  362. expect(dummy).toBe(1)
  363. stop()
  364. expect(cleanup).toHaveBeenCalledTimes(2)
  365. })
  366. it('cleanup registration (with source)', async () => {
  367. const count = ref(0)
  368. const cleanup = vi.fn()
  369. let dummy
  370. const stop = watch(count, (count, prevCount, onCleanup) => {
  371. onCleanup(cleanup)
  372. dummy = count
  373. })
  374. count.value++
  375. await nextTick()
  376. expect(cleanup).toHaveBeenCalledTimes(0)
  377. expect(dummy).toBe(1)
  378. count.value++
  379. await nextTick()
  380. expect(cleanup).toHaveBeenCalledTimes(1)
  381. expect(dummy).toBe(2)
  382. stop()
  383. expect(cleanup).toHaveBeenCalledTimes(2)
  384. })
  385. it('flush timing: pre (default)', async () => {
  386. const count = ref(0)
  387. const count2 = ref(0)
  388. let callCount = 0
  389. let result1
  390. let result2
  391. const assertion = vi.fn((count, count2Value) => {
  392. callCount++
  393. // on mount, the watcher callback should be called before DOM render
  394. // on update, should be called before the count is updated
  395. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  396. result1 = serializeInner(root) === expectedDOM
  397. // in a pre-flush callback, all state should have been updated
  398. const expectedState = callCount - 1
  399. result2 = count === expectedState && count2Value === expectedState
  400. })
  401. const Comp = {
  402. setup() {
  403. watchEffect(() => {
  404. assertion(count.value, count2.value)
  405. })
  406. return () => count.value
  407. },
  408. }
  409. const root = nodeOps.createElement('div')
  410. render(h(Comp), root)
  411. expect(assertion).toHaveBeenCalledTimes(1)
  412. expect(result1).toBe(true)
  413. expect(result2).toBe(true)
  414. count.value++
  415. count2.value++
  416. await nextTick()
  417. // two mutations should result in 1 callback execution
  418. expect(assertion).toHaveBeenCalledTimes(2)
  419. expect(result1).toBe(true)
  420. expect(result2).toBe(true)
  421. })
  422. it('flush timing: post', async () => {
  423. const count = ref(0)
  424. let result
  425. const assertion = vi.fn(count => {
  426. result = serializeInner(root) === `${count}`
  427. })
  428. const Comp = {
  429. setup() {
  430. watchEffect(
  431. () => {
  432. assertion(count.value)
  433. },
  434. { flush: 'post' },
  435. )
  436. return () => count.value
  437. },
  438. }
  439. const root = nodeOps.createElement('div')
  440. render(h(Comp), root)
  441. expect(assertion).toHaveBeenCalledTimes(1)
  442. expect(result).toBe(true)
  443. count.value++
  444. await nextTick()
  445. expect(assertion).toHaveBeenCalledTimes(2)
  446. expect(result).toBe(true)
  447. })
  448. it('watchPostEffect', async () => {
  449. const count = ref(0)
  450. let result
  451. const assertion = vi.fn(count => {
  452. result = serializeInner(root) === `${count}`
  453. })
  454. const Comp = {
  455. setup() {
  456. watchPostEffect(() => {
  457. assertion(count.value)
  458. })
  459. return () => count.value
  460. },
  461. }
  462. const root = nodeOps.createElement('div')
  463. render(h(Comp), root)
  464. expect(assertion).toHaveBeenCalledTimes(1)
  465. expect(result).toBe(true)
  466. count.value++
  467. await nextTick()
  468. expect(assertion).toHaveBeenCalledTimes(2)
  469. expect(result).toBe(true)
  470. })
  471. it('flush timing: sync', async () => {
  472. const count = ref(0)
  473. const count2 = ref(0)
  474. let callCount = 0
  475. let result1
  476. let result2
  477. const assertion = vi.fn(count => {
  478. callCount++
  479. // on mount, the watcher callback should be called before DOM render
  480. // on update, should be called before the count is updated
  481. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  482. result1 = serializeInner(root) === expectedDOM
  483. // in a sync callback, state mutation on the next line should not have
  484. // executed yet on the 2nd call, but will be on the 3rd call.
  485. const expectedState = callCount < 3 ? 0 : 1
  486. result2 = count2.value === expectedState
  487. })
  488. const Comp = {
  489. setup() {
  490. watchEffect(
  491. () => {
  492. assertion(count.value)
  493. },
  494. {
  495. flush: 'sync',
  496. },
  497. )
  498. return () => count.value
  499. },
  500. }
  501. const root = nodeOps.createElement('div')
  502. render(h(Comp), root)
  503. expect(assertion).toHaveBeenCalledTimes(1)
  504. expect(result1).toBe(true)
  505. expect(result2).toBe(true)
  506. count.value++
  507. count2.value++
  508. await nextTick()
  509. expect(assertion).toHaveBeenCalledTimes(3)
  510. expect(result1).toBe(true)
  511. expect(result2).toBe(true)
  512. })
  513. it('watchSyncEffect', async () => {
  514. const count = ref(0)
  515. const count2 = ref(0)
  516. let callCount = 0
  517. let result1
  518. let result2
  519. const assertion = vi.fn(count => {
  520. callCount++
  521. // on mount, the watcher callback should be called before DOM render
  522. // on update, should be called before the count is updated
  523. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  524. result1 = serializeInner(root) === expectedDOM
  525. // in a sync callback, state mutation on the next line should not have
  526. // executed yet on the 2nd call, but will be on the 3rd call.
  527. const expectedState = callCount < 3 ? 0 : 1
  528. result2 = count2.value === expectedState
  529. })
  530. const Comp = {
  531. setup() {
  532. watchSyncEffect(() => {
  533. assertion(count.value)
  534. })
  535. return () => count.value
  536. },
  537. }
  538. const root = nodeOps.createElement('div')
  539. render(h(Comp), root)
  540. expect(assertion).toHaveBeenCalledTimes(1)
  541. expect(result1).toBe(true)
  542. expect(result2).toBe(true)
  543. count.value++
  544. count2.value++
  545. await nextTick()
  546. expect(assertion).toHaveBeenCalledTimes(3)
  547. expect(result1).toBe(true)
  548. expect(result2).toBe(true)
  549. })
  550. it('should not fire on component unmount w/ flush: post', async () => {
  551. const toggle = ref(true)
  552. const cb = vi.fn()
  553. const Comp = {
  554. setup() {
  555. watch(toggle, cb, { flush: 'post' })
  556. },
  557. render() {},
  558. }
  559. const App = {
  560. render() {
  561. return toggle.value ? h(Comp) : null
  562. },
  563. }
  564. render(h(App), nodeOps.createElement('div'))
  565. expect(cb).not.toHaveBeenCalled()
  566. toggle.value = false
  567. await nextTick()
  568. expect(cb).not.toHaveBeenCalled()
  569. })
  570. // #2291
  571. it('should not fire on component unmount w/ flush: pre', async () => {
  572. const toggle = ref(true)
  573. const cb = vi.fn()
  574. const Comp = {
  575. setup() {
  576. watch(toggle, cb, { flush: 'pre' })
  577. },
  578. render() {},
  579. }
  580. const App = {
  581. render() {
  582. return toggle.value ? h(Comp) : null
  583. },
  584. }
  585. render(h(App), nodeOps.createElement('div'))
  586. expect(cb).not.toHaveBeenCalled()
  587. toggle.value = false
  588. await nextTick()
  589. expect(cb).not.toHaveBeenCalled()
  590. })
  591. // #7030
  592. it('should not fire on child component unmount w/ flush: pre', async () => {
  593. const visible = ref(true)
  594. const cb = vi.fn()
  595. const Parent = defineComponent({
  596. props: ['visible'],
  597. render() {
  598. return visible.value ? h(Comp) : null
  599. },
  600. })
  601. const Comp = {
  602. setup() {
  603. watch(visible, cb, { flush: 'pre' })
  604. },
  605. render() {},
  606. }
  607. const App = {
  608. render() {
  609. return h(Parent, {
  610. visible: visible.value,
  611. })
  612. },
  613. }
  614. render(h(App), nodeOps.createElement('div'))
  615. expect(cb).not.toHaveBeenCalled()
  616. visible.value = false
  617. await nextTick()
  618. expect(cb).not.toHaveBeenCalled()
  619. })
  620. // #7030
  621. it('flush: pre watcher in child component should not fire before parent update', async () => {
  622. const b = ref(0)
  623. const calls: string[] = []
  624. const Comp = {
  625. setup() {
  626. watch(
  627. () => b.value,
  628. val => {
  629. calls.push('watcher child')
  630. },
  631. { flush: 'pre' },
  632. )
  633. return () => {
  634. b.value
  635. calls.push('render child')
  636. }
  637. },
  638. }
  639. const Parent = {
  640. props: ['a'],
  641. setup() {
  642. watch(
  643. () => b.value,
  644. val => {
  645. calls.push('watcher parent')
  646. },
  647. { flush: 'pre' },
  648. )
  649. return () => {
  650. b.value
  651. calls.push('render parent')
  652. return h(Comp)
  653. }
  654. },
  655. }
  656. const App = {
  657. render() {
  658. return h(Parent, {
  659. a: b.value,
  660. })
  661. },
  662. }
  663. render(h(App), nodeOps.createElement('div'))
  664. expect(calls).toEqual(['render parent', 'render child'])
  665. b.value++
  666. await nextTick()
  667. expect(calls).toEqual([
  668. 'render parent',
  669. 'render child',
  670. 'watcher parent',
  671. 'render parent',
  672. 'watcher child',
  673. 'render child',
  674. ])
  675. })
  676. // #1763
  677. it('flush: pre watcher watching props should fire before child update', async () => {
  678. const a = ref(0)
  679. const b = ref(0)
  680. const c = ref(0)
  681. const calls: string[] = []
  682. const Comp = {
  683. props: ['a', 'b'],
  684. setup(props: any) {
  685. watch(
  686. () => props.a + props.b,
  687. () => {
  688. calls.push('watcher 1')
  689. c.value++
  690. },
  691. { flush: 'pre' },
  692. )
  693. // #1777 chained pre-watcher
  694. watch(
  695. c,
  696. () => {
  697. calls.push('watcher 2')
  698. },
  699. { flush: 'pre' },
  700. )
  701. return () => {
  702. c.value
  703. calls.push('render')
  704. }
  705. },
  706. }
  707. const App = {
  708. render() {
  709. return h(Comp, { a: a.value, b: b.value })
  710. },
  711. }
  712. render(h(App), nodeOps.createElement('div'))
  713. expect(calls).toEqual(['render'])
  714. // both props are updated
  715. // should trigger pre-flush watcher first and only once
  716. // then trigger child render
  717. a.value++
  718. b.value++
  719. await nextTick()
  720. expect(calls).toEqual(['render', 'watcher 1', 'watcher 2', 'render'])
  721. })
  722. // #5721
  723. it('flush: pre triggered in component setup should be buffered and called before mounted', () => {
  724. const count = ref(0)
  725. const calls: string[] = []
  726. const App = {
  727. render() {},
  728. setup() {
  729. watch(
  730. count,
  731. () => {
  732. calls.push('watch ' + count.value)
  733. },
  734. { flush: 'pre' },
  735. )
  736. onMounted(() => {
  737. calls.push('mounted')
  738. })
  739. // mutate multiple times
  740. count.value++
  741. count.value++
  742. count.value++
  743. },
  744. }
  745. render(h(App), nodeOps.createElement('div'))
  746. expect(calls).toMatchObject(['watch 3', 'mounted'])
  747. })
  748. // #1852
  749. it('flush: post watcher should fire after template refs updated', async () => {
  750. const toggle = ref(false)
  751. let dom: TestElement | null = null
  752. const App = {
  753. setup() {
  754. const domRef = ref<TestElement | null>(null)
  755. watch(
  756. toggle,
  757. () => {
  758. dom = domRef.value
  759. },
  760. { flush: 'post' },
  761. )
  762. return () => {
  763. return toggle.value ? h('p', { ref: domRef }) : null
  764. }
  765. },
  766. }
  767. render(h(App), nodeOps.createElement('div'))
  768. expect(dom).toBe(null)
  769. toggle.value = true
  770. await nextTick()
  771. expect(dom!.tag).toBe('p')
  772. })
  773. it('deep', async () => {
  774. const state = reactive({
  775. nested: {
  776. count: ref(0),
  777. },
  778. array: [1, 2, 3],
  779. map: new Map([
  780. ['a', 1],
  781. ['b', 2],
  782. ]),
  783. set: new Set([1, 2, 3]),
  784. })
  785. let dummy
  786. watch(
  787. () => state,
  788. state => {
  789. dummy = [
  790. state.nested.count,
  791. state.array[0],
  792. state.map.get('a'),
  793. state.set.has(1),
  794. ]
  795. },
  796. { deep: true },
  797. )
  798. state.nested.count++
  799. await nextTick()
  800. expect(dummy).toEqual([1, 1, 1, true])
  801. // nested array mutation
  802. state.array[0] = 2
  803. await nextTick()
  804. expect(dummy).toEqual([1, 2, 1, true])
  805. // nested map mutation
  806. state.map.set('a', 2)
  807. await nextTick()
  808. expect(dummy).toEqual([1, 2, 2, true])
  809. // nested set mutation
  810. state.set.delete(1)
  811. await nextTick()
  812. expect(dummy).toEqual([1, 2, 2, false])
  813. })
  814. it('watching deep ref', async () => {
  815. const count = ref(0)
  816. const double = computed(() => count.value * 2)
  817. const state = reactive([count, double])
  818. let dummy
  819. watch(
  820. () => state,
  821. state => {
  822. dummy = [state[0].value, state[1].value]
  823. },
  824. { deep: true },
  825. )
  826. count.value++
  827. await nextTick()
  828. expect(dummy).toEqual([1, 2])
  829. })
  830. it('deep with symbols', async () => {
  831. const symbol1 = Symbol()
  832. const symbol2 = Symbol()
  833. const symbol3 = Symbol()
  834. const symbol4 = Symbol()
  835. const raw: any = {
  836. [symbol1]: {
  837. [symbol2]: 1,
  838. },
  839. }
  840. Object.defineProperty(raw, symbol3, {
  841. writable: true,
  842. enumerable: false,
  843. value: 1,
  844. })
  845. const state = reactive(raw)
  846. const spy = vi.fn()
  847. watch(() => state, spy, { deep: true })
  848. await nextTick()
  849. expect(spy).toHaveBeenCalledTimes(0)
  850. state[symbol1][symbol2] = 2
  851. await nextTick()
  852. expect(spy).toHaveBeenCalledTimes(1)
  853. // Non-enumerable properties don't trigger deep watchers
  854. state[symbol3] = 3
  855. await nextTick()
  856. expect(spy).toHaveBeenCalledTimes(1)
  857. // Adding a new symbol property
  858. state[symbol4] = 1
  859. await nextTick()
  860. expect(spy).toHaveBeenCalledTimes(2)
  861. // Removing a symbol property
  862. delete state[symbol4]
  863. await nextTick()
  864. expect(spy).toHaveBeenCalledTimes(3)
  865. })
  866. it('immediate', async () => {
  867. const count = ref(0)
  868. const cb = vi.fn()
  869. watch(count, cb, { immediate: true })
  870. expect(cb).toHaveBeenCalledTimes(1)
  871. count.value++
  872. await nextTick()
  873. expect(cb).toHaveBeenCalledTimes(2)
  874. })
  875. it('immediate: triggers when initial value is null', async () => {
  876. const state = ref(null)
  877. const spy = vi.fn()
  878. watch(() => state.value, spy, { immediate: true })
  879. expect(spy).toHaveBeenCalled()
  880. })
  881. it('immediate: triggers when initial value is undefined', async () => {
  882. const state = ref()
  883. const spy = vi.fn()
  884. watch(() => state.value, spy, { immediate: true })
  885. expect(spy).toHaveBeenCalledWith(undefined, undefined, expect.any(Function))
  886. state.value = 3
  887. await nextTick()
  888. expect(spy).toHaveBeenCalledTimes(2)
  889. // testing if undefined can trigger the watcher
  890. state.value = undefined
  891. await nextTick()
  892. expect(spy).toHaveBeenCalledTimes(3)
  893. // it shouldn't trigger if the same value is set
  894. state.value = undefined
  895. await nextTick()
  896. expect(spy).toHaveBeenCalledTimes(3)
  897. })
  898. it('warn immediate option when using effect', async () => {
  899. const count = ref(0)
  900. let dummy
  901. watchEffect(
  902. () => {
  903. dummy = count.value
  904. },
  905. // @ts-expect-error
  906. { immediate: false },
  907. )
  908. expect(dummy).toBe(0)
  909. expect(`"immediate" option is only respected`).toHaveBeenWarned()
  910. count.value++
  911. await nextTick()
  912. expect(dummy).toBe(1)
  913. })
  914. it('warn and not respect deep option when using effect', async () => {
  915. const arr = ref([1, [2]])
  916. const spy = vi.fn()
  917. watchEffect(
  918. () => {
  919. spy()
  920. return arr
  921. },
  922. // @ts-expect-error
  923. { deep: true },
  924. )
  925. expect(spy).toHaveBeenCalledTimes(1)
  926. ;(arr.value[1] as Array<number>)[0] = 3
  927. await nextTick()
  928. expect(spy).toHaveBeenCalledTimes(1)
  929. expect(`"deep" option is only respected`).toHaveBeenWarned()
  930. })
  931. it('onTrack', async () => {
  932. const events: DebuggerEvent[] = []
  933. let dummy
  934. const onTrack = vi.fn((e: DebuggerEvent) => {
  935. events.push(e)
  936. })
  937. const obj = reactive({ foo: 1, bar: 2 })
  938. watchEffect(
  939. () => {
  940. dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
  941. },
  942. { onTrack },
  943. )
  944. await nextTick()
  945. expect(dummy).toEqual([1, true, ['foo', 'bar']])
  946. expect(onTrack).toHaveBeenCalledTimes(3)
  947. expect(events).toMatchObject([
  948. {
  949. target: obj,
  950. type: TrackOpTypes.GET,
  951. key: 'foo',
  952. },
  953. {
  954. target: obj,
  955. type: TrackOpTypes.HAS,
  956. key: 'bar',
  957. },
  958. {
  959. target: obj,
  960. type: TrackOpTypes.ITERATE,
  961. key: ITERATE_KEY,
  962. },
  963. ])
  964. })
  965. it('onTrigger', async () => {
  966. const events: DebuggerEvent[] = []
  967. let dummy
  968. const onTrigger = vi.fn((e: DebuggerEvent) => {
  969. events.push(e)
  970. })
  971. const obj = reactive<{ foo?: number }>({ foo: 1 })
  972. watchEffect(
  973. () => {
  974. dummy = obj.foo
  975. },
  976. { onTrigger },
  977. )
  978. await nextTick()
  979. expect(dummy).toBe(1)
  980. obj.foo!++
  981. await nextTick()
  982. expect(dummy).toBe(2)
  983. expect(onTrigger).toHaveBeenCalledTimes(1)
  984. expect(events[0]).toMatchObject({
  985. type: TriggerOpTypes.SET,
  986. key: 'foo',
  987. oldValue: 1,
  988. newValue: 2,
  989. })
  990. delete obj.foo
  991. await nextTick()
  992. expect(dummy).toBeUndefined()
  993. expect(onTrigger).toHaveBeenCalledTimes(2)
  994. expect(events[1]).toMatchObject({
  995. type: TriggerOpTypes.DELETE,
  996. key: 'foo',
  997. oldValue: 2,
  998. })
  999. })
  1000. it('should work sync', () => {
  1001. const v = ref(1)
  1002. let calls = 0
  1003. watch(
  1004. v,
  1005. () => {
  1006. ++calls
  1007. },
  1008. {
  1009. flush: 'sync',
  1010. },
  1011. )
  1012. expect(calls).toBe(0)
  1013. v.value++
  1014. expect(calls).toBe(1)
  1015. })
  1016. test('should force trigger on triggerRef when watching a shallow ref', async () => {
  1017. const v = shallowRef({ a: 1 })
  1018. let sideEffect = 0
  1019. watch(v, obj => {
  1020. sideEffect = obj.a
  1021. })
  1022. v.value = v.value
  1023. await nextTick()
  1024. // should not trigger
  1025. expect(sideEffect).toBe(0)
  1026. v.value.a++
  1027. await nextTick()
  1028. // should not trigger
  1029. expect(sideEffect).toBe(0)
  1030. triggerRef(v)
  1031. await nextTick()
  1032. // should trigger now
  1033. expect(sideEffect).toBe(2)
  1034. })
  1035. test('should force trigger on triggerRef when watching multiple sources: shallow ref array', async () => {
  1036. const v = shallowRef([] as any)
  1037. const spy = vi.fn()
  1038. watch([v], () => {
  1039. spy()
  1040. })
  1041. v.value.push(1)
  1042. triggerRef(v)
  1043. await nextTick()
  1044. // should trigger now
  1045. expect(spy).toHaveBeenCalledTimes(1)
  1046. })
  1047. test('should force trigger on triggerRef with toRef from reactive', async () => {
  1048. const foo = reactive({ bar: 1 })
  1049. const bar = toRef(foo, 'bar')
  1050. const spy = vi.fn()
  1051. watchEffect(() => {
  1052. bar.value
  1053. spy()
  1054. })
  1055. expect(spy).toHaveBeenCalledTimes(1)
  1056. triggerRef(bar)
  1057. await nextTick()
  1058. // should trigger now
  1059. expect(spy).toHaveBeenCalledTimes(2)
  1060. })
  1061. // #2125
  1062. test('watchEffect should not recursively trigger itself', async () => {
  1063. const spy = vi.fn()
  1064. const price = ref(10)
  1065. const history = ref<number[]>([])
  1066. watchEffect(() => {
  1067. history.value.push(price.value)
  1068. spy()
  1069. })
  1070. await nextTick()
  1071. expect(spy).toHaveBeenCalledTimes(1)
  1072. })
  1073. // #2231
  1074. test('computed refs should not trigger watch if value has no change', async () => {
  1075. const spy = vi.fn()
  1076. const source = ref(0)
  1077. const price = computed(() => source.value === 0)
  1078. watch(price, spy)
  1079. source.value++
  1080. await nextTick()
  1081. source.value++
  1082. await nextTick()
  1083. expect(spy).toHaveBeenCalledTimes(1)
  1084. })
  1085. // https://github.com/vuejs/core/issues/2381
  1086. test('$watch should always register its effects with its own instance', async () => {
  1087. let instance: ComponentInternalInstance | null
  1088. let _show: Ref<boolean>
  1089. const Child = defineComponent({
  1090. render: () => h('div'),
  1091. mounted() {
  1092. instance = getCurrentInstance()
  1093. },
  1094. unmounted() {},
  1095. })
  1096. const Comp = defineComponent({
  1097. setup() {
  1098. const comp = ref<ComponentPublicInstance | undefined>()
  1099. const show = ref(true)
  1100. _show = show
  1101. return { comp, show }
  1102. },
  1103. render() {
  1104. return this.show
  1105. ? h(Child, {
  1106. ref: vm => void (this.comp = vm as ComponentPublicInstance),
  1107. })
  1108. : null
  1109. },
  1110. mounted() {
  1111. // this call runs while Comp is currentInstance, but
  1112. // the effect for this `$watch` should nonetheless be registered with Child
  1113. this.comp!.$watch(
  1114. () => this.show,
  1115. () => void 0,
  1116. )
  1117. },
  1118. })
  1119. render(h(Comp), nodeOps.createElement('div'))
  1120. expect(instance!).toBeDefined()
  1121. expect(instance!.scope.effects).toBeInstanceOf(Array)
  1122. // includes the component's own render effect AND the watcher effect
  1123. expect(instance!.scope.effects.length).toBe(2)
  1124. _show!.value = false
  1125. await nextTick()
  1126. await nextTick()
  1127. expect(instance!.scope.effects[0].active).toBe(false)
  1128. })
  1129. test('this.$watch should pass `this.proxy` to watch source as the first argument ', () => {
  1130. let instance: any
  1131. const source = vi.fn()
  1132. const Comp = defineComponent({
  1133. render() {},
  1134. created(this: any) {
  1135. instance = this
  1136. this.$watch(source, function () {})
  1137. },
  1138. })
  1139. const root = nodeOps.createElement('div')
  1140. createApp(Comp).mount(root)
  1141. expect(instance).toBeDefined()
  1142. expect(source.mock.calls.some(args => args.includes(instance)))
  1143. })
  1144. test('should not leak `this.proxy` to setup()', () => {
  1145. const source = vi.fn()
  1146. const Comp = defineComponent({
  1147. render() {},
  1148. setup() {
  1149. watch(source, () => {})
  1150. },
  1151. })
  1152. const root = nodeOps.createElement('div')
  1153. createApp(Comp).mount(root)
  1154. // should not have any arguments
  1155. expect(source.mock.calls[0]).toMatchObject([])
  1156. })
  1157. // #2728
  1158. test('pre watcher callbacks should not track dependencies', async () => {
  1159. const a = ref(0)
  1160. const b = ref(0)
  1161. const updated = vi.fn()
  1162. const Child = defineComponent({
  1163. props: ['a'],
  1164. updated,
  1165. watch: {
  1166. a() {
  1167. b.value
  1168. },
  1169. },
  1170. render() {
  1171. return h('div', this.a)
  1172. },
  1173. })
  1174. const Parent = defineComponent({
  1175. render() {
  1176. return h(Child, { a: a.value })
  1177. },
  1178. })
  1179. const root = nodeOps.createElement('div')
  1180. createApp(Parent).mount(root)
  1181. a.value++
  1182. await nextTick()
  1183. expect(updated).toHaveBeenCalledTimes(1)
  1184. b.value++
  1185. await nextTick()
  1186. // should not track b as dependency of Child
  1187. expect(updated).toHaveBeenCalledTimes(1)
  1188. })
  1189. test('watching keypath', async () => {
  1190. const spy = vi.fn()
  1191. const Comp = defineComponent({
  1192. render() {},
  1193. data() {
  1194. return {
  1195. a: {
  1196. b: 1,
  1197. },
  1198. }
  1199. },
  1200. watch: {
  1201. 'a.b': spy,
  1202. },
  1203. created(this: any) {
  1204. this.$watch('a.b', spy)
  1205. },
  1206. mounted(this: any) {
  1207. this.a.b++
  1208. },
  1209. })
  1210. const root = nodeOps.createElement('div')
  1211. createApp(Comp).mount(root)
  1212. await nextTick()
  1213. expect(spy).toHaveBeenCalledTimes(2)
  1214. })
  1215. it('watching sources: ref<any[]>', async () => {
  1216. const foo = ref([1])
  1217. const spy = vi.fn()
  1218. watch(foo, () => {
  1219. spy()
  1220. })
  1221. foo.value = foo.value.slice()
  1222. await nextTick()
  1223. expect(spy).toBeCalledTimes(1)
  1224. })
  1225. it('watching multiple sources: computed', async () => {
  1226. let count = 0
  1227. const value = ref('1')
  1228. const plus = computed(() => !!value.value)
  1229. watch([plus], () => {
  1230. count++
  1231. })
  1232. value.value = '2'
  1233. await nextTick()
  1234. expect(plus.value).toBe(true)
  1235. expect(count).toBe(0)
  1236. })
  1237. // #4158
  1238. test('watch should not register in owner component if created inside detached scope', () => {
  1239. let instance: ComponentInternalInstance
  1240. const Comp = {
  1241. setup() {
  1242. instance = getCurrentInstance()!
  1243. effectScope(true).run(() => {
  1244. watch(
  1245. () => 1,
  1246. () => {},
  1247. )
  1248. })
  1249. return () => ''
  1250. },
  1251. }
  1252. const root = nodeOps.createElement('div')
  1253. createApp(Comp).mount(root)
  1254. // should not record watcher in detached scope and only the instance's
  1255. // own update effect
  1256. expect(instance!.scope.effects.length).toBe(1)
  1257. })
  1258. test('watchEffect should keep running if created in a detached scope', async () => {
  1259. const trigger = ref(0)
  1260. let countWE = 0
  1261. let countW = 0
  1262. const Comp = {
  1263. setup() {
  1264. effectScope(true).run(() => {
  1265. watchEffect(() => {
  1266. trigger.value
  1267. countWE++
  1268. })
  1269. watch(trigger, () => countW++)
  1270. })
  1271. return () => ''
  1272. },
  1273. }
  1274. const root = nodeOps.createElement('div')
  1275. render(h(Comp), root)
  1276. // only watchEffect as ran so far
  1277. expect(countWE).toBe(1)
  1278. expect(countW).toBe(0)
  1279. trigger.value++
  1280. await nextTick()
  1281. // both watchers run while component is mounted
  1282. expect(countWE).toBe(2)
  1283. expect(countW).toBe(1)
  1284. render(null, root) // unmount
  1285. await nextTick()
  1286. trigger.value++
  1287. await nextTick()
  1288. // both watchers run again event though component has been unmounted
  1289. expect(countWE).toBe(3)
  1290. expect(countW).toBe(2)
  1291. })
  1292. const options = [
  1293. { name: 'only trigger once watch' },
  1294. {
  1295. deep: true,
  1296. name: 'only trigger once watch with deep',
  1297. },
  1298. {
  1299. flush: 'sync',
  1300. name: 'only trigger once watch with flush: sync',
  1301. },
  1302. {
  1303. flush: 'pre',
  1304. name: 'only trigger once watch with flush: pre',
  1305. },
  1306. {
  1307. immediate: true,
  1308. name: 'only trigger once watch with immediate',
  1309. },
  1310. ] as const
  1311. test.each(options)('$name', async option => {
  1312. const count = ref(0)
  1313. const cb = vi.fn()
  1314. watch(count, cb, { once: true, ...option })
  1315. count.value++
  1316. await nextTick()
  1317. expect(count.value).toBe(1)
  1318. expect(cb).toHaveBeenCalledTimes(1)
  1319. count.value++
  1320. await nextTick()
  1321. expect(count.value).toBe(2)
  1322. expect(cb).toHaveBeenCalledTimes(1)
  1323. })
  1324. // #5151
  1325. test('OnCleanup also needs to be cleaned,', async () => {
  1326. const spy1 = vi.fn()
  1327. const spy2 = vi.fn()
  1328. const num = ref(0)
  1329. watch(num, (value, oldValue, onCleanup) => {
  1330. if (value > 1) {
  1331. return
  1332. }
  1333. spy1()
  1334. onCleanup(() => {
  1335. // OnCleanup also needs to be cleaned
  1336. spy2()
  1337. })
  1338. })
  1339. num.value++
  1340. await nextTick()
  1341. expect(spy1).toHaveBeenCalledTimes(1)
  1342. expect(spy2).toHaveBeenCalledTimes(0)
  1343. num.value++
  1344. await nextTick()
  1345. expect(spy1).toHaveBeenCalledTimes(1)
  1346. expect(spy2).toHaveBeenCalledTimes(1)
  1347. num.value++
  1348. await nextTick()
  1349. // would not be calld when value>1
  1350. expect(spy1).toHaveBeenCalledTimes(1)
  1351. expect(spy2).toHaveBeenCalledTimes(1)
  1352. })
  1353. test("effect should be removed from scope's effects after it is stopped", () => {
  1354. const num = ref(0)
  1355. let unwatch: () => void
  1356. let instance: ComponentInternalInstance
  1357. const Comp = {
  1358. setup() {
  1359. instance = getCurrentInstance()!
  1360. unwatch = watch(num, () => {
  1361. console.log(num.value)
  1362. })
  1363. return () => null
  1364. },
  1365. }
  1366. const root = nodeOps.createElement('div')
  1367. createApp(Comp).mount(root)
  1368. expect(instance!.scope.effects.length).toBe(2)
  1369. unwatch!()
  1370. expect(instance!.scope.effects.length).toBe(1)
  1371. const scope = effectScope()
  1372. scope.run(() => {
  1373. unwatch = watch(num, () => {
  1374. console.log(num.value)
  1375. })
  1376. })
  1377. expect(scope.effects.length).toBe(1)
  1378. unwatch!()
  1379. expect(scope.effects.length).toBe(0)
  1380. })
  1381. test('circular reference', async () => {
  1382. const obj = { a: 1 }
  1383. // @ts-expect-error
  1384. obj.b = obj
  1385. const foo = ref(obj)
  1386. const spy = vi.fn()
  1387. watch(foo, spy, { deep: true })
  1388. // @ts-expect-error
  1389. foo.value.b.a = 2
  1390. await nextTick()
  1391. expect(spy).toHaveBeenCalledTimes(1)
  1392. expect(foo.value.a).toBe(2)
  1393. })
  1394. })