apiWatch.spec.ts 26 KB

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