apiWatch.spec.ts 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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-ignore
  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-ignore
  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-ignore
  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: 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. // @ts-ignore
  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. // #2125
  801. test('watchEffect should not recursively trigger itself', async () => {
  802. const spy = jest.fn()
  803. const price = ref(10)
  804. const history = ref<number[]>([])
  805. watchEffect(() => {
  806. history.value.push(price.value)
  807. spy()
  808. })
  809. await nextTick()
  810. expect(spy).toHaveBeenCalledTimes(1)
  811. })
  812. // #2231
  813. test('computed refs should not trigger watch if value has no change', async () => {
  814. const spy = jest.fn()
  815. const source = ref(0)
  816. const price = computed(() => source.value === 0)
  817. watch(price, spy)
  818. source.value++
  819. await nextTick()
  820. source.value++
  821. await nextTick()
  822. expect(spy).toHaveBeenCalledTimes(1)
  823. })
  824. // https://github.com/vuejs/core/issues/2381
  825. test('$watch should always register its effects with its own instance', async () => {
  826. let instance: ComponentInternalInstance | null
  827. let _show: Ref<boolean>
  828. const Child = defineComponent({
  829. render: () => h('div'),
  830. mounted() {
  831. instance = getCurrentInstance()
  832. },
  833. unmounted() {}
  834. })
  835. const Comp = defineComponent({
  836. setup() {
  837. const comp = ref<ComponentPublicInstance | undefined>()
  838. const show = ref(true)
  839. _show = show
  840. return { comp, show }
  841. },
  842. render() {
  843. return this.show
  844. ? h(Child, {
  845. ref: vm => void (this.comp = vm as ComponentPublicInstance)
  846. })
  847. : null
  848. },
  849. mounted() {
  850. // this call runs while Comp is currentInstance, but
  851. // the effect for this `$watch` should nontheless be registered with Child
  852. this.comp!.$watch(
  853. () => this.show,
  854. () => void 0
  855. )
  856. }
  857. })
  858. render(h(Comp), nodeOps.createElement('div'))
  859. expect(instance!).toBeDefined()
  860. expect(instance!.scope.effects).toBeInstanceOf(Array)
  861. // includes the component's own render effect AND the watcher effect
  862. expect(instance!.scope.effects.length).toBe(2)
  863. _show!.value = false
  864. await nextTick()
  865. await nextTick()
  866. expect(instance!.scope.effects[0].active).toBe(false)
  867. })
  868. test('this.$watch should pass `this.proxy` to watch source as the first argument ', () => {
  869. let instance: any
  870. const source = jest.fn()
  871. const Comp = defineComponent({
  872. render() {},
  873. created(this: any) {
  874. instance = this
  875. this.$watch(source, function () {})
  876. }
  877. })
  878. const root = nodeOps.createElement('div')
  879. createApp(Comp).mount(root)
  880. expect(instance).toBeDefined()
  881. expect(source).toHaveBeenCalledWith(instance)
  882. })
  883. test('should not leak `this.proxy` to setup()', () => {
  884. const source = jest.fn()
  885. const Comp = defineComponent({
  886. render() {},
  887. setup() {
  888. watch(source, () => {})
  889. }
  890. })
  891. const root = nodeOps.createElement('div')
  892. createApp(Comp).mount(root)
  893. // should not have any arguments
  894. expect(source.mock.calls[0]).toMatchObject([])
  895. })
  896. // #2728
  897. test('pre watcher callbacks should not track dependencies', async () => {
  898. const a = ref(0)
  899. const b = ref(0)
  900. const updated = jest.fn()
  901. const Child = defineComponent({
  902. props: ['a'],
  903. updated,
  904. watch: {
  905. a() {
  906. b.value
  907. }
  908. },
  909. render() {
  910. return h('div', this.a)
  911. }
  912. })
  913. const Parent = defineComponent({
  914. render() {
  915. return h(Child, { a: a.value })
  916. }
  917. })
  918. const root = nodeOps.createElement('div')
  919. createApp(Parent).mount(root)
  920. a.value++
  921. await nextTick()
  922. expect(updated).toHaveBeenCalledTimes(1)
  923. b.value++
  924. await nextTick()
  925. // should not track b as dependency of Child
  926. expect(updated).toHaveBeenCalledTimes(1)
  927. })
  928. test('watching keypath', async () => {
  929. const spy = jest.fn()
  930. const Comp = defineComponent({
  931. render() {},
  932. data() {
  933. return {
  934. a: {
  935. b: 1
  936. }
  937. }
  938. },
  939. watch: {
  940. 'a.b': spy
  941. },
  942. created(this: any) {
  943. this.$watch('a.b', spy)
  944. },
  945. mounted(this: any) {
  946. this.a.b++
  947. }
  948. })
  949. const root = nodeOps.createElement('div')
  950. createApp(Comp).mount(root)
  951. await nextTick()
  952. expect(spy).toHaveBeenCalledTimes(2)
  953. })
  954. it('watching sources: ref<any[]>', async () => {
  955. const foo = ref([1])
  956. const spy = jest.fn()
  957. watch(foo, () => {
  958. spy()
  959. })
  960. foo.value = foo.value.slice()
  961. await nextTick()
  962. expect(spy).toBeCalledTimes(1)
  963. })
  964. it('watching multiple sources: computed', async () => {
  965. let count = 0
  966. const value = ref('1')
  967. const plus = computed(() => !!value.value)
  968. watch([plus], () => {
  969. count++
  970. })
  971. value.value = '2'
  972. await nextTick()
  973. expect(plus.value).toBe(true)
  974. expect(count).toBe(0)
  975. })
  976. // #4158
  977. test('watch should not register in owner component if created inside detached scope', () => {
  978. let instance: ComponentInternalInstance
  979. const Comp = {
  980. setup() {
  981. instance = getCurrentInstance()!
  982. effectScope(true).run(() => {
  983. watch(
  984. () => 1,
  985. () => {}
  986. )
  987. })
  988. return () => ''
  989. }
  990. }
  991. const root = nodeOps.createElement('div')
  992. createApp(Comp).mount(root)
  993. // should not record watcher in detached scope and only the instance's
  994. // own update effect
  995. expect(instance!.scope.effects.length).toBe(1)
  996. })
  997. })