apiWatch.spec.ts 26 KB

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