apiWatch.spec.ts 33 KB

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