apiWatch.spec.ts 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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. // #2291
  457. it('should not fire on component unmount w/ flush: pre', async () => {
  458. const toggle = ref(true)
  459. const cb = jest.fn()
  460. const Comp = {
  461. setup() {
  462. watch(toggle, cb, { flush: 'pre' })
  463. },
  464. render() {}
  465. }
  466. const App = {
  467. render() {
  468. return toggle.value ? h(Comp) : null
  469. }
  470. }
  471. render(h(App), nodeOps.createElement('div'))
  472. expect(cb).not.toHaveBeenCalled()
  473. toggle.value = false
  474. await nextTick()
  475. expect(cb).not.toHaveBeenCalled()
  476. })
  477. // #1763
  478. it('flush: pre watcher watching props should fire before child update', async () => {
  479. const a = ref(0)
  480. const b = ref(0)
  481. const c = ref(0)
  482. const calls: string[] = []
  483. const Comp = {
  484. props: ['a', 'b'],
  485. setup(props: any) {
  486. watch(
  487. () => props.a + props.b,
  488. () => {
  489. calls.push('watcher 1')
  490. c.value++
  491. },
  492. { flush: 'pre' }
  493. )
  494. // #1777 chained pre-watcher
  495. watch(
  496. c,
  497. () => {
  498. calls.push('watcher 2')
  499. },
  500. { flush: 'pre' }
  501. )
  502. return () => {
  503. c.value
  504. calls.push('render')
  505. }
  506. }
  507. }
  508. const App = {
  509. render() {
  510. return h(Comp, { a: a.value, b: b.value })
  511. }
  512. }
  513. render(h(App), nodeOps.createElement('div'))
  514. expect(calls).toEqual(['render'])
  515. // both props are updated
  516. // should trigger pre-flush watcher first and only once
  517. // then trigger child render
  518. a.value++
  519. b.value++
  520. await nextTick()
  521. expect(calls).toEqual(['render', 'watcher 1', 'watcher 2', 'render'])
  522. })
  523. // #5721
  524. it('flush: pre triggered in component setup should be buffered and called before mounted', () => {
  525. const count = ref(0)
  526. const calls: string[] = []
  527. const App = {
  528. render() {},
  529. setup() {
  530. watch(
  531. count,
  532. () => {
  533. calls.push('watch ' + count.value)
  534. },
  535. { flush: 'pre' }
  536. )
  537. onMounted(() => {
  538. calls.push('mounted')
  539. })
  540. // mutate multiple times
  541. count.value++
  542. count.value++
  543. count.value++
  544. }
  545. }
  546. render(h(App), nodeOps.createElement('div'))
  547. expect(calls).toMatchObject(['watch 3', 'mounted'])
  548. })
  549. // #1852
  550. it('flush: post watcher should fire after template refs updated', async () => {
  551. const toggle = ref(false)
  552. let dom: TestElement | null = null
  553. const App = {
  554. setup() {
  555. const domRef = ref<TestElement | null>(null)
  556. watch(
  557. toggle,
  558. () => {
  559. dom = domRef.value
  560. },
  561. { flush: 'post' }
  562. )
  563. return () => {
  564. return toggle.value ? h('p', { ref: domRef }) : null
  565. }
  566. }
  567. }
  568. render(h(App), nodeOps.createElement('div'))
  569. expect(dom).toBe(null)
  570. toggle.value = true
  571. await nextTick()
  572. expect(dom!.tag).toBe('p')
  573. })
  574. it('deep', async () => {
  575. const state = reactive({
  576. nested: {
  577. count: ref(0)
  578. },
  579. array: [1, 2, 3],
  580. map: new Map([
  581. ['a', 1],
  582. ['b', 2]
  583. ]),
  584. set: new Set([1, 2, 3])
  585. })
  586. let dummy
  587. watch(
  588. () => state,
  589. state => {
  590. dummy = [
  591. state.nested.count,
  592. state.array[0],
  593. state.map.get('a'),
  594. state.set.has(1)
  595. ]
  596. },
  597. { deep: true }
  598. )
  599. state.nested.count++
  600. await nextTick()
  601. expect(dummy).toEqual([1, 1, 1, true])
  602. // nested array mutation
  603. state.array[0] = 2
  604. await nextTick()
  605. expect(dummy).toEqual([1, 2, 1, true])
  606. // nested map mutation
  607. state.map.set('a', 2)
  608. await nextTick()
  609. expect(dummy).toEqual([1, 2, 2, true])
  610. // nested set mutation
  611. state.set.delete(1)
  612. await nextTick()
  613. expect(dummy).toEqual([1, 2, 2, false])
  614. })
  615. it('watching deep ref', async () => {
  616. const count = ref(0)
  617. const double = computed(() => count.value * 2)
  618. const state = reactive([count, double])
  619. let dummy
  620. watch(
  621. () => state,
  622. state => {
  623. dummy = [state[0].value, state[1].value]
  624. },
  625. { deep: true }
  626. )
  627. count.value++
  628. await nextTick()
  629. expect(dummy).toEqual([1, 2])
  630. })
  631. it('immediate', async () => {
  632. const count = ref(0)
  633. const cb = jest.fn()
  634. watch(count, cb, { immediate: true })
  635. expect(cb).toHaveBeenCalledTimes(1)
  636. count.value++
  637. await nextTick()
  638. expect(cb).toHaveBeenCalledTimes(2)
  639. })
  640. it('immediate: triggers when initial value is null', async () => {
  641. const state = ref(null)
  642. const spy = jest.fn()
  643. watch(() => state.value, spy, { immediate: true })
  644. expect(spy).toHaveBeenCalled()
  645. })
  646. it('immediate: triggers when initial value is undefined', async () => {
  647. const state = ref()
  648. const spy = jest.fn()
  649. watch(() => state.value, spy, { immediate: true })
  650. expect(spy).toHaveBeenCalled()
  651. state.value = 3
  652. await nextTick()
  653. expect(spy).toHaveBeenCalledTimes(2)
  654. // testing if undefined can trigger the watcher
  655. state.value = undefined
  656. await nextTick()
  657. expect(spy).toHaveBeenCalledTimes(3)
  658. // it shouldn't trigger if the same value is set
  659. state.value = undefined
  660. await nextTick()
  661. expect(spy).toHaveBeenCalledTimes(3)
  662. })
  663. it('warn immediate option when using effect', async () => {
  664. const count = ref(0)
  665. let dummy
  666. watchEffect(
  667. () => {
  668. dummy = count.value
  669. },
  670. // @ts-expect-error
  671. { immediate: false }
  672. )
  673. expect(dummy).toBe(0)
  674. expect(`"immediate" option is only respected`).toHaveBeenWarned()
  675. count.value++
  676. await nextTick()
  677. expect(dummy).toBe(1)
  678. })
  679. it('warn and not respect deep option when using effect', async () => {
  680. const arr = ref([1, [2]])
  681. const spy = jest.fn()
  682. watchEffect(
  683. () => {
  684. spy()
  685. return arr
  686. },
  687. // @ts-expect-error
  688. { deep: true }
  689. )
  690. expect(spy).toHaveBeenCalledTimes(1)
  691. ;(arr.value[1] as Array<number>)[0] = 3
  692. await nextTick()
  693. expect(spy).toHaveBeenCalledTimes(1)
  694. expect(`"deep" option is only respected`).toHaveBeenWarned()
  695. })
  696. it('onTrack', async () => {
  697. const events: DebuggerEvent[] = []
  698. let dummy
  699. const onTrack = jest.fn((e: DebuggerEvent) => {
  700. events.push(e)
  701. })
  702. const obj = reactive({ foo: 1, bar: 2 })
  703. watchEffect(
  704. () => {
  705. dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
  706. },
  707. { onTrack }
  708. )
  709. await nextTick()
  710. expect(dummy).toEqual([1, true, ['foo', 'bar']])
  711. expect(onTrack).toHaveBeenCalledTimes(3)
  712. expect(events).toMatchObject([
  713. {
  714. target: obj,
  715. type: TrackOpTypes.GET,
  716. key: 'foo'
  717. },
  718. {
  719. target: obj,
  720. type: TrackOpTypes.HAS,
  721. key: 'bar'
  722. },
  723. {
  724. target: obj,
  725. type: TrackOpTypes.ITERATE,
  726. key: ITERATE_KEY
  727. }
  728. ])
  729. })
  730. it('onTrigger', async () => {
  731. const events: DebuggerEvent[] = []
  732. let dummy
  733. const onTrigger = jest.fn((e: DebuggerEvent) => {
  734. events.push(e)
  735. })
  736. const obj = reactive<{ foo?: number }>({ foo: 1 })
  737. watchEffect(
  738. () => {
  739. dummy = obj.foo
  740. },
  741. { onTrigger }
  742. )
  743. await nextTick()
  744. expect(dummy).toBe(1)
  745. obj.foo!++
  746. await nextTick()
  747. expect(dummy).toBe(2)
  748. expect(onTrigger).toHaveBeenCalledTimes(1)
  749. expect(events[0]).toMatchObject({
  750. type: TriggerOpTypes.SET,
  751. key: 'foo',
  752. oldValue: 1,
  753. newValue: 2
  754. })
  755. delete obj.foo
  756. await nextTick()
  757. expect(dummy).toBeUndefined()
  758. expect(onTrigger).toHaveBeenCalledTimes(2)
  759. expect(events[1]).toMatchObject({
  760. type: TriggerOpTypes.DELETE,
  761. key: 'foo',
  762. oldValue: 2
  763. })
  764. })
  765. it('should work sync', () => {
  766. const v = ref(1)
  767. let calls = 0
  768. watch(
  769. v,
  770. () => {
  771. ++calls
  772. },
  773. {
  774. flush: 'sync'
  775. }
  776. )
  777. expect(calls).toBe(0)
  778. v.value++
  779. expect(calls).toBe(1)
  780. })
  781. test('should force trigger on triggerRef when watching a shallow ref', async () => {
  782. const v = shallowRef({ a: 1 })
  783. let sideEffect = 0
  784. watch(v, obj => {
  785. sideEffect = obj.a
  786. })
  787. v.value = v.value
  788. await nextTick()
  789. // should not trigger
  790. expect(sideEffect).toBe(0)
  791. v.value.a++
  792. await nextTick()
  793. // should not trigger
  794. expect(sideEffect).toBe(0)
  795. triggerRef(v)
  796. await nextTick()
  797. // should trigger now
  798. expect(sideEffect).toBe(2)
  799. })
  800. test('should force trigger on triggerRef when watching multiple sources: shallow ref array', async () => {
  801. const v = shallowRef([] as any)
  802. const spy = jest.fn()
  803. watch([v], () => {
  804. spy()
  805. })
  806. v.value.push(1)
  807. triggerRef(v)
  808. await nextTick()
  809. // should trigger now
  810. expect(spy).toHaveBeenCalledTimes(1)
  811. })
  812. // #2125
  813. test('watchEffect should not recursively trigger itself', async () => {
  814. const spy = jest.fn()
  815. const price = ref(10)
  816. const history = ref<number[]>([])
  817. watchEffect(() => {
  818. history.value.push(price.value)
  819. spy()
  820. })
  821. await nextTick()
  822. expect(spy).toHaveBeenCalledTimes(1)
  823. })
  824. // #2231
  825. test('computed refs should not trigger watch if value has no change', async () => {
  826. const spy = jest.fn()
  827. const source = ref(0)
  828. const price = computed(() => source.value === 0)
  829. watch(price, spy)
  830. source.value++
  831. await nextTick()
  832. source.value++
  833. await nextTick()
  834. expect(spy).toHaveBeenCalledTimes(1)
  835. })
  836. // https://github.com/vuejs/core/issues/2381
  837. test('$watch should always register its effects with its own instance', async () => {
  838. let instance: ComponentInternalInstance | null
  839. let _show: Ref<boolean>
  840. const Child = defineComponent({
  841. render: () => h('div'),
  842. mounted() {
  843. instance = getCurrentInstance()
  844. },
  845. unmounted() {}
  846. })
  847. const Comp = defineComponent({
  848. setup() {
  849. const comp = ref<ComponentPublicInstance | undefined>()
  850. const show = ref(true)
  851. _show = show
  852. return { comp, show }
  853. },
  854. render() {
  855. return this.show
  856. ? h(Child, {
  857. ref: vm => void (this.comp = vm as ComponentPublicInstance)
  858. })
  859. : null
  860. },
  861. mounted() {
  862. // this call runs while Comp is currentInstance, but
  863. // the effect for this `$watch` should nontheless be registered with Child
  864. this.comp!.$watch(
  865. () => this.show,
  866. () => void 0
  867. )
  868. }
  869. })
  870. render(h(Comp), nodeOps.createElement('div'))
  871. expect(instance!).toBeDefined()
  872. expect(instance!.scope.effects).toBeInstanceOf(Array)
  873. // includes the component's own render effect AND the watcher effect
  874. expect(instance!.scope.effects.length).toBe(2)
  875. _show!.value = false
  876. await nextTick()
  877. await nextTick()
  878. expect(instance!.scope.effects[0].active).toBe(false)
  879. })
  880. test('this.$watch should pass `this.proxy` to watch source as the first argument ', () => {
  881. let instance: any
  882. const source = jest.fn()
  883. const Comp = defineComponent({
  884. render() {},
  885. created(this: any) {
  886. instance = this
  887. this.$watch(source, function () {})
  888. }
  889. })
  890. const root = nodeOps.createElement('div')
  891. createApp(Comp).mount(root)
  892. expect(instance).toBeDefined()
  893. expect(source).toHaveBeenCalledWith(instance)
  894. })
  895. test('should not leak `this.proxy` to setup()', () => {
  896. const source = jest.fn()
  897. const Comp = defineComponent({
  898. render() {},
  899. setup() {
  900. watch(source, () => {})
  901. }
  902. })
  903. const root = nodeOps.createElement('div')
  904. createApp(Comp).mount(root)
  905. // should not have any arguments
  906. expect(source.mock.calls[0]).toMatchObject([])
  907. })
  908. // #2728
  909. test('pre watcher callbacks should not track dependencies', async () => {
  910. const a = ref(0)
  911. const b = ref(0)
  912. const updated = jest.fn()
  913. const Child = defineComponent({
  914. props: ['a'],
  915. updated,
  916. watch: {
  917. a() {
  918. b.value
  919. }
  920. },
  921. render() {
  922. return h('div', this.a)
  923. }
  924. })
  925. const Parent = defineComponent({
  926. render() {
  927. return h(Child, { a: a.value })
  928. }
  929. })
  930. const root = nodeOps.createElement('div')
  931. createApp(Parent).mount(root)
  932. a.value++
  933. await nextTick()
  934. expect(updated).toHaveBeenCalledTimes(1)
  935. b.value++
  936. await nextTick()
  937. // should not track b as dependency of Child
  938. expect(updated).toHaveBeenCalledTimes(1)
  939. })
  940. test('watching keypath', async () => {
  941. const spy = jest.fn()
  942. const Comp = defineComponent({
  943. render() {},
  944. data() {
  945. return {
  946. a: {
  947. b: 1
  948. }
  949. }
  950. },
  951. watch: {
  952. 'a.b': spy
  953. },
  954. created(this: any) {
  955. this.$watch('a.b', spy)
  956. },
  957. mounted(this: any) {
  958. this.a.b++
  959. }
  960. })
  961. const root = nodeOps.createElement('div')
  962. createApp(Comp).mount(root)
  963. await nextTick()
  964. expect(spy).toHaveBeenCalledTimes(2)
  965. })
  966. it('watching sources: ref<any[]>', async () => {
  967. const foo = ref([1])
  968. const spy = jest.fn()
  969. watch(foo, () => {
  970. spy()
  971. })
  972. foo.value = foo.value.slice()
  973. await nextTick()
  974. expect(spy).toBeCalledTimes(1)
  975. })
  976. it('watching multiple sources: computed', async () => {
  977. let count = 0
  978. const value = ref('1')
  979. const plus = computed(() => !!value.value)
  980. watch([plus], () => {
  981. count++
  982. })
  983. value.value = '2'
  984. await nextTick()
  985. expect(plus.value).toBe(true)
  986. expect(count).toBe(0)
  987. })
  988. // #4158
  989. test('watch should not register in owner component if created inside detached scope', () => {
  990. let instance: ComponentInternalInstance
  991. const Comp = {
  992. setup() {
  993. instance = getCurrentInstance()!
  994. effectScope(true).run(() => {
  995. watch(
  996. () => 1,
  997. () => {}
  998. )
  999. })
  1000. return () => ''
  1001. }
  1002. }
  1003. const root = nodeOps.createElement('div')
  1004. createApp(Comp).mount(root)
  1005. // should not record watcher in detached scope and only the instance's
  1006. // own update effect
  1007. expect(instance!.scope.effects.length).toBe(1)
  1008. })
  1009. })