apiWatch.spec.ts 26 KB

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