apiWatch.spec.ts 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. import Vue from 'vue'
  2. import {
  3. watch,
  4. watchEffect,
  5. watchPostEffect,
  6. watchSyncEffect,
  7. reactive,
  8. computed,
  9. ref,
  10. triggerRef,
  11. shallowRef,
  12. h,
  13. onMounted,
  14. getCurrentInstance,
  15. effectScope,
  16. TrackOpTypes,
  17. TriggerOpTypes,
  18. DebuggerEvent
  19. } from 'v3'
  20. import { nextTick } from 'core/util'
  21. import { set } from 'core/observer'
  22. import { Component } from 'types/component'
  23. // reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
  24. describe('api: watch', () => {
  25. it('effect', async () => {
  26. const state = reactive({ count: 0 })
  27. let dummy
  28. watchEffect(() => {
  29. dummy = state.count
  30. })
  31. expect(dummy).toBe(0)
  32. state.count++
  33. await nextTick()
  34. expect(dummy).toBe(1)
  35. })
  36. it('watching single source: getter', async () => {
  37. const state = reactive({ count: 0 })
  38. let dummy
  39. watch(
  40. () => state.count,
  41. (count, prevCount) => {
  42. dummy = [count, prevCount]
  43. // assert types
  44. count + 1
  45. if (prevCount) {
  46. prevCount + 1
  47. }
  48. }
  49. )
  50. state.count++
  51. await nextTick()
  52. expect(dummy).toMatchObject([1, 0])
  53. })
  54. it('watching single source: ref', async () => {
  55. const count = ref(0)
  56. let dummy
  57. watch(count, (count, prevCount) => {
  58. dummy = [count, prevCount]
  59. // assert types
  60. count + 1
  61. if (prevCount) {
  62. prevCount + 1
  63. }
  64. })
  65. count.value++
  66. await nextTick()
  67. expect(dummy).toMatchObject([1, 0])
  68. })
  69. it('watching single source: array', async () => {
  70. const array = reactive({ a: [] as number[] }).a
  71. const spy = vi.fn()
  72. watch(array, spy)
  73. array.push(1)
  74. await nextTick()
  75. expect(spy).toBeCalledTimes(1)
  76. expect(spy).toBeCalledWith([1], expect.anything(), expect.anything())
  77. })
  78. it('should not fire if watched getter result did not change', async () => {
  79. const spy = vi.fn()
  80. const n = ref(0)
  81. watch(() => n.value % 2, spy)
  82. n.value++
  83. await nextTick()
  84. expect(spy).toBeCalledTimes(1)
  85. n.value += 2
  86. await nextTick()
  87. // should not be called again because getter result did not change
  88. expect(spy).toBeCalledTimes(1)
  89. })
  90. it('watching single source: computed ref', async () => {
  91. const count = ref(0)
  92. const plus = computed(() => count.value + 1)
  93. let dummy
  94. watch(plus, (count, prevCount) => {
  95. dummy = [count, prevCount]
  96. // assert types
  97. count + 1
  98. if (prevCount) {
  99. prevCount + 1
  100. }
  101. })
  102. count.value++
  103. await nextTick()
  104. expect(dummy).toMatchObject([2, 1])
  105. })
  106. it('watching primitive with deep: true', async () => {
  107. const count = ref(0)
  108. let dummy
  109. watch(
  110. count,
  111. (c, prevCount) => {
  112. dummy = [c, prevCount]
  113. },
  114. {
  115. deep: true
  116. }
  117. )
  118. count.value++
  119. await nextTick()
  120. expect(dummy).toMatchObject([1, 0])
  121. })
  122. it('directly watching reactive object (with automatic deep: true)', async () => {
  123. const src = reactive({
  124. count: 0
  125. })
  126. let dummy
  127. watch(src, ({ count }) => {
  128. dummy = count
  129. })
  130. src.count++
  131. await nextTick()
  132. expect(dummy).toBe(1)
  133. })
  134. it('deep watch w/ raw refs', async () => {
  135. const count = ref(0)
  136. const src = reactive({
  137. arr: [count]
  138. })
  139. let dummy
  140. watch(src, ({ arr: [{ value }] }) => {
  141. dummy = value
  142. })
  143. count.value++
  144. await nextTick()
  145. expect(dummy).toBe(1)
  146. })
  147. it('watching multiple sources', async () => {
  148. const state = reactive({ count: 1 })
  149. const count = ref(1)
  150. const plus = computed(() => count.value + 1)
  151. let dummy
  152. watch([() => state.count, count, plus], (vals, oldVals) => {
  153. dummy = [vals, oldVals]
  154. // assert types
  155. vals.concat(1)
  156. oldVals.concat(1)
  157. })
  158. state.count++
  159. count.value++
  160. await nextTick()
  161. expect(dummy).toMatchObject([
  162. [2, 2, 3],
  163. [1, 1, 2]
  164. ])
  165. })
  166. it('watching multiple sources: readonly array', async () => {
  167. const state = reactive({ count: 1 })
  168. const status = ref(false)
  169. let dummy
  170. watch([() => state.count, status] as const, (vals, oldVals) => {
  171. dummy = [vals, oldVals]
  172. const [count] = vals
  173. const [, oldStatus] = oldVals
  174. // assert types
  175. count + 1
  176. oldStatus === true
  177. })
  178. state.count++
  179. status.value = true
  180. await nextTick()
  181. expect(dummy).toMatchObject([
  182. [2, true],
  183. [1, false]
  184. ])
  185. })
  186. it('watching multiple sources: reactive object (with automatic deep: true)', async () => {
  187. const src = reactive({ count: 0 })
  188. let dummy
  189. watch([src], ([state]) => {
  190. dummy = state
  191. // assert types
  192. state.count === 1
  193. })
  194. src.count++
  195. await nextTick()
  196. expect(dummy).toMatchObject({ count: 1 })
  197. })
  198. it('warn invalid watch source', () => {
  199. // @ts-expect-error
  200. watch(1, () => {})
  201. expect(`Invalid watch source`).toHaveBeenWarned()
  202. })
  203. it('warn invalid watch source: multiple sources', () => {
  204. watch([1], () => {})
  205. expect(`Invalid watch source`).toHaveBeenWarned()
  206. })
  207. it('stopping the watcher (effect)', async () => {
  208. const state = reactive({ count: 0 })
  209. let dummy
  210. const stop = watchEffect(() => {
  211. dummy = state.count
  212. })
  213. expect(dummy).toBe(0)
  214. stop()
  215. state.count++
  216. await nextTick()
  217. // should not update
  218. expect(dummy).toBe(0)
  219. })
  220. it('stopping the watcher (with source)', async () => {
  221. const state = reactive({ count: 0 })
  222. let dummy
  223. const stop = watch(
  224. () => state.count,
  225. count => {
  226. dummy = count
  227. }
  228. )
  229. state.count++
  230. await nextTick()
  231. expect(dummy).toBe(1)
  232. stop()
  233. state.count++
  234. await nextTick()
  235. // should not update
  236. expect(dummy).toBe(1)
  237. })
  238. it('cleanup registration (effect)', async () => {
  239. const state = reactive({ count: 0 })
  240. const cleanup = vi.fn()
  241. let dummy
  242. const stop = watchEffect(onCleanup => {
  243. onCleanup(cleanup)
  244. dummy = state.count
  245. })
  246. expect(dummy).toBe(0)
  247. state.count++
  248. await nextTick()
  249. expect(cleanup).toHaveBeenCalledTimes(1)
  250. expect(dummy).toBe(1)
  251. stop()
  252. expect(cleanup).toHaveBeenCalledTimes(2)
  253. })
  254. it('cleanup registration (with source)', async () => {
  255. const count = ref(0)
  256. const cleanup = vi.fn()
  257. let dummy
  258. const stop = watch(count, (count, prevCount, onCleanup) => {
  259. onCleanup(cleanup)
  260. dummy = count
  261. })
  262. count.value++
  263. await nextTick()
  264. expect(cleanup).toHaveBeenCalledTimes(0)
  265. expect(dummy).toBe(1)
  266. count.value++
  267. await nextTick()
  268. expect(cleanup).toHaveBeenCalledTimes(1)
  269. expect(dummy).toBe(2)
  270. stop()
  271. expect(cleanup).toHaveBeenCalledTimes(2)
  272. })
  273. it('flush timing: pre (default)', async () => {
  274. const count = ref(0)
  275. const count2 = ref(0)
  276. let callCount = 0
  277. let result1
  278. let result2
  279. const assertion = vi.fn((count, count2Value) => {
  280. callCount++
  281. // on mount, the watcher callback should be called before DOM render
  282. // on update, should be called before the count is updated
  283. const expectedDOM =
  284. callCount === 1 ? `<div></div>` : `<div>${count - 1}</div>`
  285. result1 = container.innerHTML === expectedDOM
  286. // in a pre-flush callback, all state should have been updated
  287. const expectedState = callCount - 1
  288. result2 = count === expectedState && count2Value === expectedState
  289. })
  290. const Comp = {
  291. setup() {
  292. watchEffect(() => {
  293. assertion(count.value, count2.value)
  294. })
  295. return () => h('div', count.value)
  296. }
  297. }
  298. const container = document.createElement('div')
  299. const root = document.createElement('div')
  300. container.appendChild(root)
  301. new Vue(Comp).$mount(root)
  302. expect(assertion).toHaveBeenCalledTimes(1)
  303. expect(result1).toBe(true)
  304. expect(result2).toBe(true)
  305. count.value++
  306. count2.value++
  307. await nextTick()
  308. // two mutations should result in 1 callback execution
  309. expect(assertion).toHaveBeenCalledTimes(2)
  310. expect(result1).toBe(true)
  311. expect(result2).toBe(true)
  312. })
  313. // #12569
  314. it('flush:pre watcher triggered before component mount (in child components)', () => {
  315. const count = ref(0)
  316. const spy = vi.fn()
  317. const Comp = {
  318. setup() {
  319. watch(count, spy)
  320. count.value++
  321. return h => h('div')
  322. }
  323. }
  324. new Vue({
  325. render: h => h(Comp)
  326. }).$mount()
  327. expect(spy).toHaveBeenCalledTimes(1)
  328. })
  329. it('flush timing: post', async () => {
  330. const count = ref(0)
  331. let result
  332. const assertion = vi.fn(count => {
  333. result = container.innerHTML === `<div>${count}</div>`
  334. })
  335. const Comp = {
  336. setup() {
  337. watchEffect(
  338. () => {
  339. assertion(count.value)
  340. },
  341. { flush: 'post' }
  342. )
  343. return () => h('div', count.value)
  344. }
  345. }
  346. const container = document.createElement('div')
  347. const root = document.createElement('div')
  348. container.appendChild(root)
  349. new Vue(Comp).$mount(root)
  350. expect(assertion).toHaveBeenCalledTimes(1)
  351. expect(result).toBe(true)
  352. count.value++
  353. await nextTick()
  354. expect(assertion).toHaveBeenCalledTimes(2)
  355. expect(result).toBe(true)
  356. })
  357. it('watchPostEffect', async () => {
  358. const count = ref(0)
  359. let result
  360. const assertion = vi.fn(count => {
  361. result = container.innerHTML === `<div>${count}</div>`
  362. })
  363. const Comp = {
  364. setup() {
  365. watchPostEffect(() => {
  366. assertion(count.value)
  367. })
  368. return () => h('div', count.value)
  369. }
  370. }
  371. const container = document.createElement('div')
  372. const root = document.createElement('div')
  373. container.appendChild(root)
  374. new Vue(Comp).$mount(root)
  375. expect(assertion).toHaveBeenCalledTimes(1)
  376. expect(result).toBe(true)
  377. count.value++
  378. await nextTick()
  379. expect(assertion).toHaveBeenCalledTimes(2)
  380. expect(result).toBe(true)
  381. })
  382. it('flush timing: sync', async () => {
  383. const count = ref(0)
  384. const count2 = ref(0)
  385. let callCount = 0
  386. let result1
  387. let result2
  388. const assertion = vi.fn(count => {
  389. callCount++
  390. // on mount, the watcher callback should be called before DOM render
  391. // on update, should be called before the count is updated
  392. const expectedDOM =
  393. callCount === 1 ? `<div></div>` : `<div>${count - 1}</div>`
  394. result1 = container.innerHTML === expectedDOM
  395. // in a sync callback, state mutation on the next line should not have
  396. // executed yet on the 2nd call, but will be on the 3rd call.
  397. const expectedState = callCount < 3 ? 0 : 1
  398. result2 = count2.value === expectedState
  399. })
  400. const Comp = {
  401. setup() {
  402. watchEffect(
  403. () => {
  404. assertion(count.value)
  405. },
  406. {
  407. flush: 'sync'
  408. }
  409. )
  410. return () => h('div', count.value)
  411. }
  412. }
  413. const container = document.createElement('div')
  414. const root = document.createElement('div')
  415. container.appendChild(root)
  416. new Vue(Comp).$mount(root)
  417. expect(assertion).toHaveBeenCalledTimes(1)
  418. expect(result1).toBe(true)
  419. expect(result2).toBe(true)
  420. count.value++
  421. count2.value++
  422. await nextTick()
  423. expect(assertion).toHaveBeenCalledTimes(3)
  424. expect(result1).toBe(true)
  425. expect(result2).toBe(true)
  426. })
  427. it('watchSyncEffect', async () => {
  428. const count = ref(0)
  429. const count2 = ref(0)
  430. let callCount = 0
  431. let result1
  432. let result2
  433. const assertion = vi.fn(count => {
  434. callCount++
  435. // on mount, the watcher callback should be called before DOM render
  436. // on update, should be called before the count is updated
  437. const expectedDOM =
  438. callCount === 1 ? `<div></div>` : `<div>${count - 1}</div>`
  439. result1 = container.innerHTML === expectedDOM
  440. // in a sync callback, state mutation on the next line should not have
  441. // executed yet on the 2nd call, but will be on the 3rd call.
  442. const expectedState = callCount < 3 ? 0 : 1
  443. result2 = count2.value === expectedState
  444. })
  445. const Comp = {
  446. setup() {
  447. watchSyncEffect(() => {
  448. assertion(count.value)
  449. })
  450. return () => h('div', count.value)
  451. }
  452. }
  453. const container = document.createElement('div')
  454. const root = document.createElement('div')
  455. container.appendChild(root)
  456. new Vue(Comp).$mount(root)
  457. expect(assertion).toHaveBeenCalledTimes(1)
  458. expect(result1).toBe(true)
  459. expect(result2).toBe(true)
  460. count.value++
  461. count2.value++
  462. await nextTick()
  463. expect(assertion).toHaveBeenCalledTimes(3)
  464. expect(result1).toBe(true)
  465. expect(result2).toBe(true)
  466. })
  467. it('should not fire on component unmount w/ flush: post', async () => {
  468. const toggle = ref(true)
  469. const cb = vi.fn()
  470. const Comp = {
  471. setup() {
  472. watch(toggle, cb, { flush: 'post' })
  473. },
  474. render() {}
  475. }
  476. const App = {
  477. render() {
  478. return toggle.value ? h(Comp) : null
  479. }
  480. }
  481. new Vue(App).$mount()
  482. expect(cb).not.toHaveBeenCalled()
  483. toggle.value = false
  484. await nextTick()
  485. expect(cb).not.toHaveBeenCalled()
  486. })
  487. it('should not fire on component unmount w/ flush: pre', async () => {
  488. const toggle = ref(true)
  489. const cb = vi.fn()
  490. const Comp = {
  491. setup() {
  492. watch(toggle, cb, { flush: 'pre' })
  493. },
  494. render() {}
  495. }
  496. const App = {
  497. render() {
  498. return toggle.value ? h(Comp) : null
  499. }
  500. }
  501. new Vue(App).$mount()
  502. expect(cb).not.toHaveBeenCalled()
  503. toggle.value = false
  504. await nextTick()
  505. expect(cb).not.toHaveBeenCalled()
  506. })
  507. // vuejs/core#1763
  508. it('flush: pre watcher watching props should fire before child update', async () => {
  509. const a = ref(0)
  510. const b = ref(0)
  511. const c = ref(0)
  512. const calls: string[] = []
  513. const Comp = {
  514. props: ['a', 'b'],
  515. setup(props: any) {
  516. watch(
  517. () => props.a + props.b,
  518. () => {
  519. calls.push('watcher 1')
  520. c.value++
  521. },
  522. { flush: 'pre' }
  523. )
  524. // vuejs/core#1777 chained pre-watcher
  525. watch(
  526. c,
  527. () => {
  528. calls.push('watcher 2')
  529. },
  530. { flush: 'pre' }
  531. )
  532. return () => {
  533. c.value
  534. calls.push('render')
  535. }
  536. }
  537. }
  538. const App = {
  539. render() {
  540. return h(Comp, { props: { a: a.value, b: b.value } })
  541. }
  542. }
  543. new Vue(App).$mount()
  544. expect(calls).toEqual(['render'])
  545. // both props are updated
  546. // should trigger pre-flush watcher first and only once
  547. // then trigger child render
  548. a.value++
  549. b.value++
  550. await nextTick()
  551. expect(calls).toEqual(['render', 'watcher 1', 'watcher 2', 'render'])
  552. })
  553. // vuejs/core#5721
  554. it('flush: pre triggered in component setup should be buffered and called before mounted', () => {
  555. const count = ref(0)
  556. const calls: string[] = []
  557. const App = {
  558. render() {},
  559. setup() {
  560. watch(
  561. count,
  562. () => {
  563. calls.push('watch ' + count.value)
  564. },
  565. { flush: 'pre' }
  566. )
  567. onMounted(() => {
  568. calls.push('mounted')
  569. })
  570. // mutate multiple times
  571. count.value++
  572. count.value++
  573. count.value++
  574. }
  575. }
  576. new Vue(App).$mount()
  577. expect(calls).toMatchObject(['watch 3', 'mounted'])
  578. })
  579. // vuejs/core#1852
  580. it('flush: post watcher should fire after template refs updated', async () => {
  581. const toggle = ref(false)
  582. let dom: HTMLElement | null = null
  583. const App = {
  584. setup() {
  585. const domRef = ref<any>(null)
  586. watch(
  587. toggle,
  588. () => {
  589. dom = domRef.value
  590. },
  591. { flush: 'post' }
  592. )
  593. return () => {
  594. return toggle.value ? h('p', { ref: domRef }) : null
  595. }
  596. }
  597. }
  598. new Vue(App).$mount()
  599. expect(dom).toBe(null)
  600. toggle.value = true
  601. await nextTick()
  602. expect(dom!.tagName).toBe('P')
  603. })
  604. it('deep', async () => {
  605. const state = reactive({
  606. nested: {
  607. count: ref(0)
  608. },
  609. array: [1, 2, 3]
  610. // map: new Map([
  611. // ['a', 1],
  612. // ['b', 2]
  613. // ]),
  614. // set: new Set([1, 2, 3])
  615. })
  616. let dummy
  617. watch(
  618. () => state,
  619. state => {
  620. dummy = [
  621. state.nested.count,
  622. state.array[0]
  623. // state.map.get('a'),
  624. // state.set.has(1)
  625. ]
  626. },
  627. { deep: true }
  628. )
  629. state.nested.count++
  630. await nextTick()
  631. expect(dummy).toEqual([1, 1])
  632. // nested array mutation
  633. set(state.array, 0, 2)
  634. await nextTick()
  635. expect(dummy).toEqual([1, 2])
  636. // nested map mutation
  637. // state.map.set('a', 2)
  638. // await nextTick()
  639. // expect(dummy).toEqual([1, 2, 2, true])
  640. // nested set mutation
  641. // state.set.delete(1)
  642. // await nextTick()
  643. // expect(dummy).toEqual([1, 2, 2, false])
  644. })
  645. it('watching deep ref', async () => {
  646. const count = ref(0)
  647. const double = computed(() => count.value * 2)
  648. const state = reactive({ count, double })
  649. let dummy
  650. watch(
  651. () => state,
  652. state => {
  653. dummy = [state.count, state.double]
  654. },
  655. { deep: true }
  656. )
  657. count.value++
  658. await nextTick()
  659. expect(dummy).toEqual([1, 2])
  660. })
  661. it('immediate', async () => {
  662. const count = ref(0)
  663. const cb = vi.fn()
  664. watch(count, cb, { immediate: true })
  665. expect(cb).toHaveBeenCalledTimes(1)
  666. count.value++
  667. await nextTick()
  668. expect(cb).toHaveBeenCalledTimes(2)
  669. })
  670. it('immediate: triggers when initial value is null', async () => {
  671. const state = ref(null)
  672. const spy = vi.fn()
  673. watch(() => state.value, spy, { immediate: true })
  674. expect(spy).toHaveBeenCalled()
  675. })
  676. it('immediate: triggers when initial value is undefined', async () => {
  677. const state = ref()
  678. const spy = vi.fn()
  679. watch(() => state.value, spy, { immediate: true })
  680. expect(spy).toHaveBeenCalled()
  681. state.value = 3
  682. await nextTick()
  683. expect(spy).toHaveBeenCalledTimes(2)
  684. // testing if undefined can trigger the watcher
  685. state.value = undefined
  686. await nextTick()
  687. expect(spy).toHaveBeenCalledTimes(3)
  688. // it shouldn't trigger if the same value is set
  689. state.value = undefined
  690. await nextTick()
  691. expect(spy).toHaveBeenCalledTimes(3)
  692. })
  693. it('warn immediate option when using effect', async () => {
  694. const count = ref(0)
  695. let dummy
  696. watchEffect(
  697. () => {
  698. dummy = count.value
  699. },
  700. // @ts-expect-error
  701. { immediate: false }
  702. )
  703. expect(dummy).toBe(0)
  704. expect(`"immediate" option is only respected`).toHaveBeenWarned()
  705. count.value++
  706. await nextTick()
  707. expect(dummy).toBe(1)
  708. })
  709. it('warn and not respect deep option when using effect', async () => {
  710. const arr = ref([1, [2]])
  711. const spy = vi.fn()
  712. watchEffect(
  713. () => {
  714. spy()
  715. return arr
  716. },
  717. // @ts-expect-error
  718. { deep: true }
  719. )
  720. expect(spy).toHaveBeenCalledTimes(1)
  721. ;(arr.value[1] as Array<number>)[0] = 3
  722. await nextTick()
  723. expect(spy).toHaveBeenCalledTimes(1)
  724. expect(`"deep" option is only respected`).toHaveBeenWarned()
  725. })
  726. it('onTrack', async () => {
  727. const events: DebuggerEvent[] = []
  728. let dummy
  729. const onTrack = vi.fn((e: DebuggerEvent) => {
  730. events.push(e)
  731. })
  732. const obj = reactive({ foo: 1 })
  733. const r = ref(2)
  734. const c = computed(() => r.value + 1)
  735. watchEffect(
  736. () => {
  737. dummy = obj.foo + r.value + c.value
  738. },
  739. { onTrack }
  740. )
  741. await nextTick()
  742. expect(dummy).toEqual(6)
  743. expect(onTrack).toHaveBeenCalledTimes(3)
  744. expect(events).toMatchObject([
  745. {
  746. target: obj,
  747. type: TrackOpTypes.GET,
  748. key: 'foo'
  749. },
  750. {
  751. target: r,
  752. type: TrackOpTypes.GET,
  753. key: 'value'
  754. },
  755. {
  756. target: c,
  757. type: TrackOpTypes.GET,
  758. key: 'value'
  759. }
  760. ])
  761. })
  762. it('onTrigger', async () => {
  763. const events: DebuggerEvent[] = []
  764. let dummy
  765. const onTrigger = vi.fn((e: DebuggerEvent) => {
  766. events.push(e)
  767. })
  768. const obj = reactive<{
  769. foo: number
  770. bar: any[]
  771. baz: { qux?: number }
  772. }>({ foo: 1, bar: [], baz: {} })
  773. watchEffect(
  774. () => {
  775. dummy = obj.foo + (obj.bar[0] || 0) + (obj.baz.qux || 0)
  776. },
  777. { onTrigger }
  778. )
  779. await nextTick()
  780. expect(dummy).toBe(1)
  781. obj.foo++
  782. await nextTick()
  783. expect(dummy).toBe(2)
  784. expect(onTrigger).toHaveBeenCalledTimes(1)
  785. expect(events[0]).toMatchObject({
  786. type: TriggerOpTypes.SET,
  787. key: 'foo',
  788. target: obj,
  789. oldValue: 1,
  790. newValue: 2
  791. })
  792. obj.bar.push(1)
  793. await nextTick()
  794. expect(dummy).toBe(3)
  795. expect(onTrigger).toHaveBeenCalledTimes(2)
  796. expect(events[1]).toMatchObject({
  797. type: TriggerOpTypes.ARRAY_MUTATION,
  798. target: obj.bar,
  799. key: 'push'
  800. })
  801. set(obj.baz, 'qux', 1)
  802. await nextTick()
  803. expect(dummy).toBe(4)
  804. expect(onTrigger).toHaveBeenCalledTimes(3)
  805. expect(events[2]).toMatchObject({
  806. type: TriggerOpTypes.ADD,
  807. target: obj.baz,
  808. key: 'qux'
  809. })
  810. })
  811. it('should work sync', () => {
  812. const v = ref(1)
  813. let calls = 0
  814. watch(
  815. v,
  816. () => {
  817. ++calls
  818. },
  819. {
  820. flush: 'sync'
  821. }
  822. )
  823. expect(calls).toBe(0)
  824. v.value++
  825. expect(calls).toBe(1)
  826. })
  827. test('should force trigger on triggerRef when watching a shallow ref', async () => {
  828. const v = shallowRef({ a: 1 })
  829. let sideEffect = 0
  830. watch(v, obj => {
  831. sideEffect = obj.a
  832. })
  833. v.value = v.value
  834. await nextTick()
  835. // should not trigger
  836. expect(sideEffect).toBe(0)
  837. v.value.a++
  838. await nextTick()
  839. // should not trigger
  840. expect(sideEffect).toBe(0)
  841. triggerRef(v)
  842. await nextTick()
  843. // should trigger now
  844. expect(sideEffect).toBe(2)
  845. })
  846. test('should force trigger on triggerRef when watching multiple sources: shallow ref array', async () => {
  847. const v = shallowRef([] as any)
  848. const spy = vi.fn()
  849. watch([v], () => {
  850. spy()
  851. })
  852. v.value.push(1)
  853. triggerRef(v)
  854. await nextTick()
  855. // should trigger now
  856. expect(spy).toHaveBeenCalledTimes(1)
  857. })
  858. // vuejs/core#2125
  859. test('watchEffect should not recursively trigger itself', async () => {
  860. const spy = vi.fn()
  861. const price = ref(10)
  862. const history = ref<number[]>([])
  863. watchEffect(() => {
  864. history.value.push(price.value)
  865. spy()
  866. })
  867. await nextTick()
  868. expect(spy).toHaveBeenCalledTimes(1)
  869. })
  870. // vuejs/core#2231
  871. test('computed refs should not trigger watch if value has no change', async () => {
  872. const spy = vi.fn()
  873. const source = ref(0)
  874. const price = computed(() => source.value === 0)
  875. watch(price, spy)
  876. source.value++
  877. await nextTick()
  878. source.value++
  879. await nextTick()
  880. expect(spy).toHaveBeenCalledTimes(1)
  881. })
  882. test('this.$watch should pass `this.proxy` to watch source as the first argument ', () => {
  883. let instance: any
  884. const source = vi.fn()
  885. const Comp = {
  886. render() {},
  887. created(this: any) {
  888. instance = this
  889. this.$watch(source, function () {})
  890. }
  891. }
  892. const root = document.createElement('div')
  893. new Vue(Comp).$mount(root)
  894. expect(instance).toBeDefined()
  895. expect(source).toHaveBeenCalledWith(instance)
  896. })
  897. test('should not leak `this.proxy` to setup()', () => {
  898. const source = vi.fn()
  899. const Comp = {
  900. render() {},
  901. setup() {
  902. watch(source, () => {})
  903. }
  904. }
  905. const root = document.createElement('div')
  906. new Vue(Comp).$mount(root)
  907. // should not have any arguments
  908. expect(source.mock.calls[0]).toMatchObject([])
  909. })
  910. // vuejs/core#2728
  911. test('pre watcher callbacks should not track dependencies', async () => {
  912. const a = ref(0)
  913. const b = ref(0)
  914. const updated = vi.fn()
  915. const cb = vi.fn()
  916. const Child = {
  917. props: ['a'],
  918. updated,
  919. watch: {
  920. a() {
  921. cb()
  922. b.value
  923. }
  924. },
  925. render() {
  926. return h('div', this.a)
  927. }
  928. }
  929. const Parent = {
  930. render() {
  931. return h(Child, { props: { a: a.value } })
  932. }
  933. }
  934. const root = document.createElement('div')
  935. new Vue(Parent).$mount(root)
  936. a.value++
  937. await nextTick()
  938. expect(updated).toHaveBeenCalledTimes(1)
  939. expect(cb).toHaveBeenCalledTimes(1)
  940. b.value++
  941. await nextTick()
  942. // should not track b as dependency of Child
  943. expect(updated).toHaveBeenCalledTimes(1)
  944. expect(cb).toHaveBeenCalledTimes(1)
  945. })
  946. it('watching sources: ref<any[]>', async () => {
  947. const foo = ref([1])
  948. const spy = vi.fn()
  949. watch(foo, () => {
  950. spy()
  951. })
  952. foo.value = foo.value.slice()
  953. await nextTick()
  954. expect(spy).toBeCalledTimes(1)
  955. })
  956. it('watching multiple sources: computed', async () => {
  957. let count = 0
  958. const value = ref('1')
  959. const plus = computed(() => !!value.value)
  960. watch([plus], () => {
  961. count++
  962. })
  963. value.value = '2'
  964. await nextTick()
  965. expect(plus.value).toBe(true)
  966. expect(count).toBe(0)
  967. })
  968. // vuejs/core#4158
  969. test('watch should not register in owner component if created inside detached scope', () => {
  970. let instance: Component
  971. const Comp = {
  972. setup() {
  973. instance = getCurrentInstance()!.proxy
  974. effectScope(true).run(() => {
  975. watch(
  976. () => 1,
  977. () => {}
  978. )
  979. })
  980. return () => ''
  981. }
  982. }
  983. const root = document.createElement('div')
  984. new Vue(Comp).$mount(root)
  985. // should not record watcher in detached scope and only the instance's
  986. // own update effect
  987. expect(instance!._scope.effects.length).toBe(1)
  988. })
  989. // #12578
  990. test('template ref triggered watcher should fire after component mount', async () => {
  991. const order: string[] = []
  992. const Child = { template: '<div/>' }
  993. const App = {
  994. setup() {
  995. const child = ref<any>(null)
  996. onMounted(() => {
  997. order.push('mounted')
  998. })
  999. watch(child, () => {
  1000. order.push('watcher')
  1001. })
  1002. return { child }
  1003. },
  1004. components: { Child },
  1005. template: `<Child ref="child"/>`
  1006. }
  1007. new Vue(App).$mount()
  1008. await nextTick()
  1009. expect(order).toMatchObject([`mounted`, `watcher`])
  1010. })
  1011. // #12624
  1012. test('pre watch triggered in mounted hook', async () => {
  1013. const spy = vi.fn()
  1014. new Vue({
  1015. setup() {
  1016. const c = ref(0)
  1017. onMounted(() => {
  1018. c.value++
  1019. })
  1020. watchEffect(() => spy(c.value))
  1021. return () => {}
  1022. }
  1023. }).$mount()
  1024. expect(spy).toHaveBeenCalledTimes(1)
  1025. await nextTick()
  1026. expect(spy).toHaveBeenCalledTimes(2)
  1027. })
  1028. // #12643
  1029. test('should trigger watch on reactive object when new property is added via set()', () => {
  1030. const spy = vi.fn()
  1031. const obj = reactive({})
  1032. watch(obj, spy, { flush: 'sync' })
  1033. set(obj, 'foo', 1)
  1034. expect(spy).toHaveBeenCalled()
  1035. })
  1036. test('should not trigger watch when calling set() on ref value', () => {
  1037. const spy = vi.fn()
  1038. const r = ref({})
  1039. watch(r, spy, { flush: 'sync' })
  1040. set(r.value, 'foo', 1)
  1041. expect(spy).not.toHaveBeenCalled()
  1042. })
  1043. // #12664
  1044. it('queueing multiple flush: post watchers', async () => {
  1045. const parentSpy = vi.fn()
  1046. const childSpy = vi.fn()
  1047. const Child = {
  1048. setup() {
  1049. const el = ref()
  1050. watch(el, childSpy, { flush: 'post' })
  1051. return { el }
  1052. },
  1053. template: `<div><span ref="el">hello child</span></div>`
  1054. }
  1055. const App = {
  1056. components: { Child },
  1057. setup() {
  1058. const el = ref()
  1059. watch(el, parentSpy, { flush: 'post' })
  1060. return { el }
  1061. },
  1062. template: `<div><Child /><span ref="el">hello app1</span></div>`
  1063. }
  1064. const container = document.createElement('div')
  1065. const root = document.createElement('div')
  1066. container.appendChild(root)
  1067. new Vue(App).$mount(root)
  1068. await nextTick()
  1069. expect(parentSpy).toHaveBeenCalledTimes(1)
  1070. expect(childSpy).toHaveBeenCalledTimes(1)
  1071. })
  1072. // #12967
  1073. test('trigger when adding new property with Vue.set (getter)', async () => {
  1074. const spy = vi.fn()
  1075. const r = reactive({ exist: 5 })
  1076. watch(() => r, spy, { deep: true })
  1077. set(r, 'add', 1)
  1078. await nextTick()
  1079. expect(spy).toHaveBeenCalledTimes(1)
  1080. })
  1081. test('trigger when adding new property with Vue.set (getter in array source)', async () => {
  1082. const spy = vi.fn()
  1083. const r = reactive({ exist: 5 })
  1084. watch([() => r], spy, { deep: true })
  1085. set(r, 'add', 1)
  1086. await nextTick()
  1087. expect(spy).toHaveBeenCalledTimes(1)
  1088. })
  1089. test('trigger when adding new property with Vue.set (reactive in array source)', async () => {
  1090. const spy = vi.fn()
  1091. const r = reactive({ exist: 5 })
  1092. watch([r], spy, { deep: true })
  1093. set(r, 'add', 1)
  1094. await nextTick()
  1095. expect(spy).toHaveBeenCalledTimes(1)
  1096. })
  1097. })