apiWatch.spec.ts 23 KB

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