apiWatch.spec.ts 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  1. import {
  2. type ComponentInternalInstance,
  3. type ComponentPublicInstance,
  4. computed,
  5. defineComponent,
  6. getCurrentInstance,
  7. nextTick,
  8. onErrorCaptured,
  9. reactive,
  10. ref,
  11. watch,
  12. watchEffect,
  13. } from '../src/index'
  14. import {
  15. type TestElement,
  16. createApp,
  17. h,
  18. nodeOps,
  19. onMounted,
  20. render,
  21. serializeInner,
  22. watchPostEffect,
  23. watchSyncEffect,
  24. } from '@vue/runtime-test'
  25. import {
  26. type DebuggerEvent,
  27. EffectFlags,
  28. ITERATE_KEY,
  29. type Ref,
  30. type ShallowRef,
  31. TrackOpTypes,
  32. TriggerOpTypes,
  33. effectScope,
  34. shallowReactive,
  35. shallowRef,
  36. toRef,
  37. triggerRef,
  38. } from '@vue/reactivity'
  39. describe('api: watch', () => {
  40. it('effect', async () => {
  41. const state = reactive({ count: 0 })
  42. let dummy
  43. watchEffect(() => {
  44. dummy = state.count
  45. })
  46. expect(dummy).toBe(0)
  47. state.count++
  48. await nextTick()
  49. expect(dummy).toBe(1)
  50. })
  51. it('watching single source: getter', async () => {
  52. const state = reactive({ count: 0 })
  53. let dummy
  54. watch(
  55. () => state.count,
  56. (count, prevCount) => {
  57. dummy = [count, prevCount]
  58. // assert types
  59. count + 1
  60. if (prevCount) {
  61. prevCount + 1
  62. }
  63. },
  64. )
  65. state.count++
  66. await nextTick()
  67. expect(dummy).toMatchObject([1, 0])
  68. })
  69. it('watching single source: ref', async () => {
  70. const count = ref(0)
  71. let dummy
  72. watch(count, (count, prevCount) => {
  73. dummy = [count, prevCount]
  74. // assert types
  75. count + 1
  76. if (prevCount) {
  77. prevCount + 1
  78. }
  79. })
  80. count.value++
  81. await nextTick()
  82. expect(dummy).toMatchObject([1, 0])
  83. })
  84. it('watching single source: array', async () => {
  85. const array = reactive([] as number[])
  86. const spy = vi.fn()
  87. watch(array, spy)
  88. array.push(1)
  89. await nextTick()
  90. expect(spy).toBeCalledTimes(1)
  91. expect(spy).toBeCalledWith([1], [1], expect.anything())
  92. })
  93. it('should not call functions inside a reactive source array', () => {
  94. const spy1 = vi.fn()
  95. const array = reactive([spy1])
  96. const spy2 = vi.fn()
  97. watch(array, spy2, { immediate: true })
  98. expect(spy1).toBeCalledTimes(0)
  99. expect(spy2).toBeCalledWith([spy1], undefined, expect.anything())
  100. })
  101. it('should not unwrap refs in a reactive source array', async () => {
  102. const val = ref({ foo: 1 })
  103. const array = reactive([val])
  104. const spy = vi.fn()
  105. watch(array, spy, { immediate: true })
  106. expect(spy).toBeCalledTimes(1)
  107. expect(spy).toBeCalledWith([val], undefined, expect.anything())
  108. // deep by default
  109. val.value.foo++
  110. await nextTick()
  111. expect(spy).toBeCalledTimes(2)
  112. expect(spy).toBeCalledWith([val], [val], expect.anything())
  113. })
  114. it('should not fire if watched getter result did not change', async () => {
  115. const spy = vi.fn()
  116. const n = ref(0)
  117. watch(() => n.value % 2, spy)
  118. n.value++
  119. await nextTick()
  120. expect(spy).toBeCalledTimes(1)
  121. n.value += 2
  122. await nextTick()
  123. // should not be called again because getter result did not change
  124. expect(spy).toBeCalledTimes(1)
  125. })
  126. it('watching single source: computed ref', async () => {
  127. const count = ref(0)
  128. const plus = computed(() => count.value + 1)
  129. let dummy
  130. watch(plus, (count, prevCount) => {
  131. dummy = [count, prevCount]
  132. // assert types
  133. count + 1
  134. if (prevCount) {
  135. prevCount + 1
  136. }
  137. })
  138. count.value++
  139. await nextTick()
  140. expect(dummy).toMatchObject([2, 1])
  141. })
  142. it('watching primitive with deep: true', async () => {
  143. const count = ref(0)
  144. let dummy
  145. watch(
  146. count,
  147. (c, prevCount) => {
  148. dummy = [c, prevCount]
  149. },
  150. {
  151. deep: true,
  152. },
  153. )
  154. count.value++
  155. await nextTick()
  156. expect(dummy).toMatchObject([1, 0])
  157. })
  158. it('directly watching reactive object (with automatic deep: true)', async () => {
  159. const src = reactive({
  160. count: 0,
  161. })
  162. let dummy
  163. watch(src, ({ count }) => {
  164. dummy = count
  165. })
  166. src.count++
  167. await nextTick()
  168. expect(dummy).toBe(1)
  169. })
  170. it('directly watching reactive object with explicit deep: false', async () => {
  171. const src = reactive({
  172. state: {
  173. count: 0,
  174. },
  175. })
  176. let dummy
  177. watch(
  178. src,
  179. ({ state }) => {
  180. dummy = state?.count
  181. },
  182. {
  183. deep: false,
  184. },
  185. )
  186. // nested should not trigger
  187. src.state.count++
  188. await nextTick()
  189. expect(dummy).toBe(undefined)
  190. // root level should trigger
  191. src.state = { count: 1 }
  192. await nextTick()
  193. expect(dummy).toBe(1)
  194. })
  195. it('directly watching reactive array with explicit deep: false', async () => {
  196. const val = ref(1)
  197. const array: any[] = reactive([val])
  198. const spy = vi.fn()
  199. watch(array, spy, { immediate: true, deep: false })
  200. expect(spy).toBeCalledTimes(1)
  201. expect(spy).toBeCalledWith([val], undefined, expect.anything())
  202. val.value++
  203. await nextTick()
  204. expect(spy).toBeCalledTimes(1)
  205. array[1] = 2
  206. await nextTick()
  207. expect(spy).toBeCalledTimes(2)
  208. expect(spy).toBeCalledWith([val, 2], [val, 2], expect.anything())
  209. })
  210. // #9916
  211. it('watching shallow reactive array with deep: false', async () => {
  212. class foo {
  213. prop1: ShallowRef<string> = shallowRef('')
  214. prop2: string = ''
  215. }
  216. const obj1 = new foo()
  217. const obj2 = new foo()
  218. const collection = shallowReactive([obj1, obj2])
  219. const cb = vi.fn()
  220. watch(collection, cb, { deep: false })
  221. collection[0].prop1.value = 'foo'
  222. await nextTick()
  223. // should not trigger
  224. expect(cb).toBeCalledTimes(0)
  225. collection.push(new foo())
  226. await nextTick()
  227. // should trigger on array self mutation
  228. expect(cb).toBeCalledTimes(1)
  229. })
  230. it('should still respect deep: true on shallowReactive source', async () => {
  231. const obj = reactive({ a: 1 })
  232. const arr = shallowReactive([obj])
  233. let dummy
  234. watch(
  235. arr,
  236. () => {
  237. dummy = arr[0].a
  238. },
  239. { deep: true },
  240. )
  241. obj.a++
  242. await nextTick()
  243. expect(dummy).toBe(2)
  244. })
  245. it('watching multiple sources', async () => {
  246. const state = reactive({ count: 1 })
  247. const count = ref(1)
  248. const plus = computed(() => count.value + 1)
  249. let dummy
  250. watch([() => state.count, count, plus], (vals, oldVals) => {
  251. dummy = [vals, oldVals]
  252. // assert types
  253. vals.concat(1)
  254. oldVals.concat(1)
  255. })
  256. state.count++
  257. count.value++
  258. await nextTick()
  259. expect(dummy).toMatchObject([
  260. [2, 2, 3],
  261. [1, 1, 2],
  262. ])
  263. })
  264. it('watching multiple sources: undefined initial values and immediate: true', async () => {
  265. const a = ref()
  266. const b = ref()
  267. let called = false
  268. watch(
  269. [a, b],
  270. ([newA, newB], [oldA, oldB]) => {
  271. called = true
  272. expect([newA, newB]).toMatchObject([undefined, undefined])
  273. expect([oldA, oldB]).toMatchObject([undefined, undefined])
  274. },
  275. { immediate: true },
  276. )
  277. await nextTick()
  278. expect(called).toBe(true)
  279. })
  280. it('watching multiple sources: readonly array', async () => {
  281. const state = reactive({ count: 1 })
  282. const status = ref(false)
  283. let dummy
  284. watch([() => state.count, status] as const, (vals, oldVals) => {
  285. dummy = [vals, oldVals]
  286. const [count] = vals
  287. const [, oldStatus] = oldVals
  288. // assert types
  289. count + 1
  290. oldStatus === true
  291. })
  292. state.count++
  293. status.value = true
  294. await nextTick()
  295. expect(dummy).toMatchObject([
  296. [2, true],
  297. [1, false],
  298. ])
  299. })
  300. it('watching multiple sources: reactive object (with automatic deep: true)', async () => {
  301. const src = reactive({ count: 0 })
  302. let dummy
  303. watch([src], ([state]) => {
  304. dummy = state
  305. // assert types
  306. state.count === 1
  307. })
  308. src.count++
  309. await nextTick()
  310. expect(dummy).toMatchObject({ count: 1 })
  311. })
  312. it('warn invalid watch source', () => {
  313. // @ts-expect-error
  314. watch(1, () => {})
  315. expect(`Invalid watch source`).toHaveBeenWarned()
  316. })
  317. it('warn invalid watch source: multiple sources', () => {
  318. watch([1], () => {})
  319. expect(`Invalid watch source`).toHaveBeenWarned()
  320. })
  321. it('stopping the watcher (effect)', async () => {
  322. const state = reactive({ count: 0 })
  323. let dummy
  324. const stop = watchEffect(() => {
  325. dummy = state.count
  326. })
  327. expect(dummy).toBe(0)
  328. stop()
  329. state.count++
  330. await nextTick()
  331. // should not update
  332. expect(dummy).toBe(0)
  333. })
  334. it('stopping the watcher (with source)', async () => {
  335. const state = reactive({ count: 0 })
  336. let dummy
  337. const stop = watch(
  338. () => state.count,
  339. count => {
  340. dummy = count
  341. },
  342. )
  343. state.count++
  344. await nextTick()
  345. expect(dummy).toBe(1)
  346. stop()
  347. state.count++
  348. await nextTick()
  349. // should not update
  350. expect(dummy).toBe(1)
  351. })
  352. it('cleanup registration (effect)', async () => {
  353. const state = reactive({ count: 0 })
  354. const cleanup = vi.fn()
  355. let dummy
  356. const stop = watchEffect(onCleanup => {
  357. onCleanup(cleanup)
  358. dummy = state.count
  359. })
  360. expect(dummy).toBe(0)
  361. state.count++
  362. await nextTick()
  363. expect(cleanup).toHaveBeenCalledTimes(1)
  364. expect(dummy).toBe(1)
  365. stop()
  366. expect(cleanup).toHaveBeenCalledTimes(2)
  367. })
  368. it('cleanup registration (with source)', async () => {
  369. const count = ref(0)
  370. const cleanup = vi.fn()
  371. let dummy
  372. const stop = watch(count, (count, prevCount, onCleanup) => {
  373. onCleanup(cleanup)
  374. dummy = count
  375. })
  376. count.value++
  377. await nextTick()
  378. expect(cleanup).toHaveBeenCalledTimes(0)
  379. expect(dummy).toBe(1)
  380. count.value++
  381. await nextTick()
  382. expect(cleanup).toHaveBeenCalledTimes(1)
  383. expect(dummy).toBe(2)
  384. stop()
  385. expect(cleanup).toHaveBeenCalledTimes(2)
  386. })
  387. it('flush timing: pre (default)', async () => {
  388. const count = ref(0)
  389. const count2 = ref(0)
  390. let callCount = 0
  391. let result1
  392. let result2
  393. const assertion = vi.fn((count, count2Value) => {
  394. callCount++
  395. // on mount, the watcher callback should be called before DOM render
  396. // on update, should be called before the count is updated
  397. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  398. result1 = serializeInner(root) === expectedDOM
  399. // in a pre-flush callback, all state should have been updated
  400. const expectedState = callCount - 1
  401. result2 = count === expectedState && count2Value === expectedState
  402. })
  403. const Comp = {
  404. setup() {
  405. watchEffect(() => {
  406. assertion(count.value, count2.value)
  407. })
  408. return () => count.value
  409. },
  410. }
  411. const root = nodeOps.createElement('div')
  412. render(h(Comp), root)
  413. expect(assertion).toHaveBeenCalledTimes(1)
  414. expect(result1).toBe(true)
  415. expect(result2).toBe(true)
  416. count.value++
  417. count2.value++
  418. await nextTick()
  419. // two mutations should result in 1 callback execution
  420. expect(assertion).toHaveBeenCalledTimes(2)
  421. expect(result1).toBe(true)
  422. expect(result2).toBe(true)
  423. })
  424. it('flush timing: post', async () => {
  425. const count = ref(0)
  426. let result
  427. const assertion = vi.fn(count => {
  428. result = serializeInner(root) === `${count}`
  429. })
  430. const Comp = {
  431. setup() {
  432. watchEffect(
  433. () => {
  434. assertion(count.value)
  435. },
  436. { flush: 'post' },
  437. )
  438. return () => count.value
  439. },
  440. }
  441. const root = nodeOps.createElement('div')
  442. render(h(Comp), root)
  443. expect(assertion).toHaveBeenCalledTimes(1)
  444. expect(result).toBe(true)
  445. count.value++
  446. await nextTick()
  447. expect(assertion).toHaveBeenCalledTimes(2)
  448. expect(result).toBe(true)
  449. })
  450. it('watchPostEffect', async () => {
  451. const count = ref(0)
  452. let result
  453. const assertion = vi.fn(count => {
  454. result = serializeInner(root) === `${count}`
  455. })
  456. const Comp = {
  457. setup() {
  458. watchPostEffect(() => {
  459. assertion(count.value)
  460. })
  461. return () => count.value
  462. },
  463. }
  464. const root = nodeOps.createElement('div')
  465. render(h(Comp), root)
  466. expect(assertion).toHaveBeenCalledTimes(1)
  467. expect(result).toBe(true)
  468. count.value++
  469. await nextTick()
  470. expect(assertion).toHaveBeenCalledTimes(2)
  471. expect(result).toBe(true)
  472. })
  473. it('flush timing: sync', async () => {
  474. const count = ref(0)
  475. const count2 = ref(0)
  476. let callCount = 0
  477. let result1
  478. let result2
  479. const assertion = vi.fn(count => {
  480. callCount++
  481. // on mount, the watcher callback should be called before DOM render
  482. // on update, should be called before the count is updated
  483. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  484. result1 = serializeInner(root) === expectedDOM
  485. // in a sync callback, state mutation on the next line should not have
  486. // executed yet on the 2nd call, but will be on the 3rd call.
  487. const expectedState = callCount < 3 ? 0 : 1
  488. result2 = count2.value === expectedState
  489. })
  490. const Comp = {
  491. setup() {
  492. watchEffect(
  493. () => {
  494. assertion(count.value)
  495. },
  496. {
  497. flush: 'sync',
  498. },
  499. )
  500. return () => count.value
  501. },
  502. }
  503. const root = nodeOps.createElement('div')
  504. render(h(Comp), root)
  505. expect(assertion).toHaveBeenCalledTimes(1)
  506. expect(result1).toBe(true)
  507. expect(result2).toBe(true)
  508. count.value++
  509. count2.value++
  510. await nextTick()
  511. expect(assertion).toHaveBeenCalledTimes(3)
  512. expect(result1).toBe(true)
  513. expect(result2).toBe(true)
  514. })
  515. it('watchSyncEffect', async () => {
  516. const count = ref(0)
  517. const count2 = ref(0)
  518. let callCount = 0
  519. let result1
  520. let result2
  521. const assertion = vi.fn(count => {
  522. callCount++
  523. // on mount, the watcher callback should be called before DOM render
  524. // on update, should be called before the count is updated
  525. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  526. result1 = serializeInner(root) === expectedDOM
  527. // in a sync callback, state mutation on the next line should not have
  528. // executed yet on the 2nd call, but will be on the 3rd call.
  529. const expectedState = callCount < 3 ? 0 : 1
  530. result2 = count2.value === expectedState
  531. })
  532. const Comp = {
  533. setup() {
  534. watchSyncEffect(() => {
  535. assertion(count.value)
  536. })
  537. return () => count.value
  538. },
  539. }
  540. const root = nodeOps.createElement('div')
  541. render(h(Comp), root)
  542. expect(assertion).toHaveBeenCalledTimes(1)
  543. expect(result1).toBe(true)
  544. expect(result2).toBe(true)
  545. count.value++
  546. count2.value++
  547. await nextTick()
  548. expect(assertion).toHaveBeenCalledTimes(3)
  549. expect(result1).toBe(true)
  550. expect(result2).toBe(true)
  551. })
  552. it('should not fire on component unmount w/ flush: post', async () => {
  553. const toggle = ref(true)
  554. const cb = vi.fn()
  555. const Comp = {
  556. setup() {
  557. watch(toggle, cb, { flush: 'post' })
  558. },
  559. render() {},
  560. }
  561. const App = {
  562. render() {
  563. return toggle.value ? h(Comp) : null
  564. },
  565. }
  566. render(h(App), nodeOps.createElement('div'))
  567. expect(cb).not.toHaveBeenCalled()
  568. toggle.value = false
  569. await nextTick()
  570. expect(cb).not.toHaveBeenCalled()
  571. })
  572. // #2291
  573. it('should not fire on component unmount w/ flush: pre', async () => {
  574. const toggle = ref(true)
  575. const cb = vi.fn()
  576. const Comp = {
  577. setup() {
  578. watch(toggle, cb, { flush: 'pre' })
  579. },
  580. render() {},
  581. }
  582. const App = {
  583. render() {
  584. return toggle.value ? h(Comp) : null
  585. },
  586. }
  587. render(h(App), nodeOps.createElement('div'))
  588. expect(cb).not.toHaveBeenCalled()
  589. toggle.value = false
  590. await nextTick()
  591. expect(cb).not.toHaveBeenCalled()
  592. })
  593. // #7030
  594. it('should not fire on child component unmount w/ flush: pre', async () => {
  595. const visible = ref(true)
  596. const cb = vi.fn()
  597. const Parent = defineComponent({
  598. props: ['visible'],
  599. render() {
  600. return visible.value ? h(Comp) : null
  601. },
  602. })
  603. const Comp = {
  604. setup() {
  605. watch(visible, cb, { flush: 'pre' })
  606. },
  607. render() {},
  608. }
  609. const App = {
  610. render() {
  611. return h(Parent, {
  612. visible: visible.value,
  613. })
  614. },
  615. }
  616. render(h(App), nodeOps.createElement('div'))
  617. expect(cb).not.toHaveBeenCalled()
  618. visible.value = false
  619. await nextTick()
  620. expect(cb).not.toHaveBeenCalled()
  621. })
  622. // #7030
  623. it('flush: pre watcher in child component should not fire before parent update', async () => {
  624. const b = ref(0)
  625. const calls: string[] = []
  626. const Comp = {
  627. setup() {
  628. watch(
  629. () => b.value,
  630. val => {
  631. calls.push('watcher child')
  632. },
  633. { flush: 'pre' },
  634. )
  635. return () => {
  636. b.value
  637. calls.push('render child')
  638. }
  639. },
  640. }
  641. const Parent = {
  642. props: ['a'],
  643. setup() {
  644. watch(
  645. () => b.value,
  646. val => {
  647. calls.push('watcher parent')
  648. },
  649. { flush: 'pre' },
  650. )
  651. return () => {
  652. b.value
  653. calls.push('render parent')
  654. return h(Comp)
  655. }
  656. },
  657. }
  658. const App = {
  659. render() {
  660. return h(Parent, {
  661. a: b.value,
  662. })
  663. },
  664. }
  665. render(h(App), nodeOps.createElement('div'))
  666. expect(calls).toEqual(['render parent', 'render child'])
  667. b.value++
  668. await nextTick()
  669. expect(calls).toEqual([
  670. 'render parent',
  671. 'render child',
  672. 'watcher parent',
  673. 'render parent',
  674. 'watcher child',
  675. 'render child',
  676. ])
  677. })
  678. // #1763
  679. it('flush: pre watcher watching props should fire before child update', async () => {
  680. const a = ref(0)
  681. const b = ref(0)
  682. const c = ref(0)
  683. const calls: string[] = []
  684. const Comp = {
  685. props: ['a', 'b'],
  686. setup(props: any) {
  687. watch(
  688. () => props.a + props.b,
  689. () => {
  690. calls.push('watcher 1')
  691. c.value++
  692. },
  693. { flush: 'pre' },
  694. )
  695. // #1777 chained pre-watcher
  696. watch(
  697. c,
  698. () => {
  699. calls.push('watcher 2')
  700. },
  701. { flush: 'pre' },
  702. )
  703. return () => {
  704. c.value
  705. calls.push('render')
  706. }
  707. },
  708. }
  709. const App = {
  710. render() {
  711. return h(Comp, { a: a.value, b: b.value })
  712. },
  713. }
  714. render(h(App), nodeOps.createElement('div'))
  715. expect(calls).toEqual(['render'])
  716. // both props are updated
  717. // should trigger pre-flush watcher first and only once
  718. // then trigger child render
  719. a.value++
  720. b.value++
  721. await nextTick()
  722. expect(calls).toEqual(['render', 'watcher 1', 'watcher 2', 'render'])
  723. })
  724. // #5721
  725. it('flush: pre triggered in component setup should be buffered and called before mounted', () => {
  726. const count = ref(0)
  727. const calls: string[] = []
  728. const App = {
  729. render() {},
  730. setup() {
  731. watch(
  732. count,
  733. () => {
  734. calls.push('watch ' + count.value)
  735. },
  736. { flush: 'pre' },
  737. )
  738. onMounted(() => {
  739. calls.push('mounted')
  740. })
  741. // mutate multiple times
  742. count.value++
  743. count.value++
  744. count.value++
  745. },
  746. }
  747. render(h(App), nodeOps.createElement('div'))
  748. expect(calls).toMatchObject(['watch 3', 'mounted'])
  749. })
  750. // #1852
  751. it('flush: post watcher should fire after template refs updated', async () => {
  752. const toggle = ref(false)
  753. let dom: TestElement | null = null
  754. const App = {
  755. setup() {
  756. const domRef = ref<TestElement | null>(null)
  757. watch(
  758. toggle,
  759. () => {
  760. dom = domRef.value
  761. },
  762. { flush: 'post' },
  763. )
  764. return () => {
  765. return toggle.value ? h('p', { ref: domRef }) : null
  766. }
  767. },
  768. }
  769. render(h(App), nodeOps.createElement('div'))
  770. expect(dom).toBe(null)
  771. toggle.value = true
  772. await nextTick()
  773. expect(dom!.tag).toBe('p')
  774. })
  775. it('deep', async () => {
  776. const state = reactive({
  777. nested: {
  778. count: ref(0),
  779. },
  780. array: [1, 2, 3],
  781. map: new Map([
  782. ['a', 1],
  783. ['b', 2],
  784. ]),
  785. set: new Set([1, 2, 3]),
  786. })
  787. let dummy
  788. watch(
  789. () => state,
  790. state => {
  791. dummy = [
  792. state.nested.count,
  793. state.array[0],
  794. state.map.get('a'),
  795. state.set.has(1),
  796. ]
  797. },
  798. { deep: true },
  799. )
  800. state.nested.count++
  801. await nextTick()
  802. expect(dummy).toEqual([1, 1, 1, true])
  803. // nested array mutation
  804. state.array[0] = 2
  805. await nextTick()
  806. expect(dummy).toEqual([1, 2, 1, true])
  807. // nested map mutation
  808. state.map.set('a', 2)
  809. await nextTick()
  810. expect(dummy).toEqual([1, 2, 2, true])
  811. // nested set mutation
  812. state.set.delete(1)
  813. await nextTick()
  814. expect(dummy).toEqual([1, 2, 2, false])
  815. })
  816. it('watching deep ref', async () => {
  817. const count = ref(0)
  818. const double = computed(() => count.value * 2)
  819. const state = reactive([count, double])
  820. let dummy
  821. watch(
  822. () => state,
  823. state => {
  824. dummy = [state[0].value, state[1].value]
  825. },
  826. { deep: true },
  827. )
  828. count.value++
  829. await nextTick()
  830. expect(dummy).toEqual([1, 2])
  831. })
  832. it('deep with symbols', async () => {
  833. const symbol1 = Symbol()
  834. const symbol2 = Symbol()
  835. const symbol3 = Symbol()
  836. const symbol4 = Symbol()
  837. const raw: any = {
  838. [symbol1]: {
  839. [symbol2]: 1,
  840. },
  841. }
  842. Object.defineProperty(raw, symbol3, {
  843. writable: true,
  844. enumerable: false,
  845. value: 1,
  846. })
  847. const state = reactive(raw)
  848. const spy = vi.fn()
  849. watch(() => state, spy, { deep: true })
  850. await nextTick()
  851. expect(spy).toHaveBeenCalledTimes(0)
  852. state[symbol1][symbol2] = 2
  853. await nextTick()
  854. expect(spy).toHaveBeenCalledTimes(1)
  855. // Non-enumerable properties don't trigger deep watchers
  856. state[symbol3] = 3
  857. await nextTick()
  858. expect(spy).toHaveBeenCalledTimes(1)
  859. // Adding a new symbol property
  860. state[symbol4] = 1
  861. await nextTick()
  862. expect(spy).toHaveBeenCalledTimes(2)
  863. // Removing a symbol property
  864. delete state[symbol4]
  865. await nextTick()
  866. expect(spy).toHaveBeenCalledTimes(3)
  867. })
  868. it('immediate', async () => {
  869. const count = ref(0)
  870. const cb = vi.fn()
  871. watch(count, cb, { immediate: true })
  872. expect(cb).toHaveBeenCalledTimes(1)
  873. count.value++
  874. await nextTick()
  875. expect(cb).toHaveBeenCalledTimes(2)
  876. })
  877. it('immediate: triggers when initial value is null', async () => {
  878. const state = ref(null)
  879. const spy = vi.fn()
  880. watch(() => state.value, spy, { immediate: true })
  881. expect(spy).toHaveBeenCalled()
  882. })
  883. it('immediate: triggers when initial value is undefined', async () => {
  884. const state = ref()
  885. const spy = vi.fn()
  886. watch(() => state.value, spy, { immediate: true })
  887. expect(spy).toHaveBeenCalledWith(undefined, undefined, expect.any(Function))
  888. state.value = 3
  889. await nextTick()
  890. expect(spy).toHaveBeenCalledTimes(2)
  891. // testing if undefined can trigger the watcher
  892. state.value = undefined
  893. await nextTick()
  894. expect(spy).toHaveBeenCalledTimes(3)
  895. // it shouldn't trigger if the same value is set
  896. state.value = undefined
  897. await nextTick()
  898. expect(spy).toHaveBeenCalledTimes(3)
  899. })
  900. it('warn immediate option when using effect', async () => {
  901. const count = ref(0)
  902. let dummy
  903. watchEffect(
  904. () => {
  905. dummy = count.value
  906. },
  907. // @ts-expect-error
  908. { immediate: false },
  909. )
  910. expect(dummy).toBe(0)
  911. expect(`"immediate" option is only respected`).toHaveBeenWarned()
  912. count.value++
  913. await nextTick()
  914. expect(dummy).toBe(1)
  915. })
  916. it('warn and not respect deep option when using effect', async () => {
  917. const arr = ref([1, [2]])
  918. const spy = vi.fn()
  919. watchEffect(
  920. () => {
  921. spy()
  922. return arr
  923. },
  924. // @ts-expect-error
  925. { deep: true },
  926. )
  927. expect(spy).toHaveBeenCalledTimes(1)
  928. ;(arr.value[1] as Array<number>)[0] = 3
  929. await nextTick()
  930. expect(spy).toHaveBeenCalledTimes(1)
  931. expect(`"deep" option is only respected`).toHaveBeenWarned()
  932. })
  933. it('onTrack', async () => {
  934. const events: DebuggerEvent[] = []
  935. let dummy
  936. const onTrack = vi.fn((e: DebuggerEvent) => {
  937. events.push(e)
  938. })
  939. const obj = reactive({ foo: 1, bar: 2 })
  940. watchEffect(
  941. () => {
  942. dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
  943. },
  944. { onTrack },
  945. )
  946. await nextTick()
  947. expect(dummy).toEqual([1, true, ['foo', 'bar']])
  948. expect(onTrack).toHaveBeenCalledTimes(3)
  949. expect(events).toMatchObject([
  950. {
  951. target: obj,
  952. type: TrackOpTypes.GET,
  953. key: 'foo',
  954. },
  955. {
  956. target: obj,
  957. type: TrackOpTypes.HAS,
  958. key: 'bar',
  959. },
  960. {
  961. target: obj,
  962. type: TrackOpTypes.ITERATE,
  963. key: ITERATE_KEY,
  964. },
  965. ])
  966. })
  967. it('onTrigger', async () => {
  968. const events: DebuggerEvent[] = []
  969. let dummy
  970. const onTrigger = vi.fn((e: DebuggerEvent) => {
  971. events.push(e)
  972. })
  973. const obj = reactive<{ foo?: number }>({ foo: 1 })
  974. watchEffect(
  975. () => {
  976. dummy = obj.foo
  977. },
  978. { onTrigger },
  979. )
  980. await nextTick()
  981. expect(dummy).toBe(1)
  982. obj.foo!++
  983. await nextTick()
  984. expect(dummy).toBe(2)
  985. expect(onTrigger).toHaveBeenCalledTimes(1)
  986. expect(events[0]).toMatchObject({
  987. type: TriggerOpTypes.SET,
  988. key: 'foo',
  989. oldValue: 1,
  990. newValue: 2,
  991. })
  992. delete obj.foo
  993. await nextTick()
  994. expect(dummy).toBeUndefined()
  995. expect(onTrigger).toHaveBeenCalledTimes(2)
  996. expect(events[1]).toMatchObject({
  997. type: TriggerOpTypes.DELETE,
  998. key: 'foo',
  999. oldValue: 2,
  1000. })
  1001. })
  1002. it('should work sync', () => {
  1003. const v = ref(1)
  1004. let calls = 0
  1005. watch(
  1006. v,
  1007. () => {
  1008. ++calls
  1009. },
  1010. {
  1011. flush: 'sync',
  1012. },
  1013. )
  1014. expect(calls).toBe(0)
  1015. v.value++
  1016. expect(calls).toBe(1)
  1017. })
  1018. test('should force trigger on triggerRef when watching a shallow ref', async () => {
  1019. const v = shallowRef({ a: 1 })
  1020. let sideEffect = 0
  1021. watch(v, obj => {
  1022. sideEffect = obj.a
  1023. })
  1024. v.value = v.value
  1025. await nextTick()
  1026. // should not trigger
  1027. expect(sideEffect).toBe(0)
  1028. v.value.a++
  1029. await nextTick()
  1030. // should not trigger
  1031. expect(sideEffect).toBe(0)
  1032. triggerRef(v)
  1033. await nextTick()
  1034. // should trigger now
  1035. expect(sideEffect).toBe(2)
  1036. })
  1037. test('should force trigger on triggerRef when watching multiple sources: shallow ref array', async () => {
  1038. const v = shallowRef([] as any)
  1039. const spy = vi.fn()
  1040. watch([v], () => {
  1041. spy()
  1042. })
  1043. v.value.push(1)
  1044. triggerRef(v)
  1045. await nextTick()
  1046. // should trigger now
  1047. expect(spy).toHaveBeenCalledTimes(1)
  1048. })
  1049. test('should force trigger on triggerRef with toRef from reactive', async () => {
  1050. const foo = reactive({ bar: 1 })
  1051. const bar = toRef(foo, 'bar')
  1052. const spy = vi.fn()
  1053. watchEffect(() => {
  1054. bar.value
  1055. spy()
  1056. })
  1057. expect(spy).toHaveBeenCalledTimes(1)
  1058. triggerRef(bar)
  1059. await nextTick()
  1060. // should trigger now
  1061. expect(spy).toHaveBeenCalledTimes(2)
  1062. })
  1063. // #2125
  1064. test('watchEffect should not recursively trigger itself', async () => {
  1065. const spy = vi.fn()
  1066. const price = ref(10)
  1067. const history = ref<number[]>([])
  1068. watchEffect(() => {
  1069. history.value.push(price.value)
  1070. spy()
  1071. })
  1072. await nextTick()
  1073. expect(spy).toHaveBeenCalledTimes(1)
  1074. })
  1075. // #2231
  1076. test('computed refs should not trigger watch if value has no change', async () => {
  1077. const spy = vi.fn()
  1078. const source = ref(0)
  1079. const price = computed(() => source.value === 0)
  1080. watch(price, spy)
  1081. source.value++
  1082. await nextTick()
  1083. source.value++
  1084. await nextTick()
  1085. expect(spy).toHaveBeenCalledTimes(1)
  1086. })
  1087. // https://github.com/vuejs/core/issues/2381
  1088. test('$watch should always register its effects with its own instance', async () => {
  1089. let instance: ComponentInternalInstance | null
  1090. let _show: Ref<boolean>
  1091. const Child = defineComponent({
  1092. render: () => h('div'),
  1093. mounted() {
  1094. instance = getCurrentInstance()
  1095. },
  1096. unmounted() {},
  1097. })
  1098. const Comp = defineComponent({
  1099. setup() {
  1100. const comp = ref<ComponentPublicInstance | undefined>()
  1101. const show = ref(true)
  1102. _show = show
  1103. return { comp, show }
  1104. },
  1105. render() {
  1106. return this.show
  1107. ? h(Child, {
  1108. ref: vm => void (this.comp = vm as ComponentPublicInstance),
  1109. })
  1110. : null
  1111. },
  1112. mounted() {
  1113. // this call runs while Comp is currentInstance, but
  1114. // the effect for this `$watch` should nonetheless be registered with Child
  1115. this.comp!.$watch(
  1116. () => this.show,
  1117. () => void 0,
  1118. )
  1119. },
  1120. })
  1121. render(h(Comp), nodeOps.createElement('div'))
  1122. expect(instance!).toBeDefined()
  1123. expect(instance!.scope.effects).toBeInstanceOf(Array)
  1124. // includes the component's own render effect AND the watcher effect
  1125. expect(instance!.scope.effects.length).toBe(2)
  1126. _show!.value = false
  1127. await nextTick()
  1128. await nextTick()
  1129. expect(instance!.scope.effects[0].flags & EffectFlags.ACTIVE).toBeFalsy()
  1130. })
  1131. test('this.$watch should pass `this.proxy` to watch source as the first argument ', () => {
  1132. let instance: any
  1133. const source = vi.fn()
  1134. const Comp = defineComponent({
  1135. render() {},
  1136. created(this: any) {
  1137. instance = this
  1138. this.$watch(source, function () {})
  1139. },
  1140. })
  1141. const root = nodeOps.createElement('div')
  1142. createApp(Comp).mount(root)
  1143. expect(instance).toBeDefined()
  1144. expect(source.mock.calls.some(args => args.includes(instance)))
  1145. })
  1146. test('should not leak `this.proxy` to setup()', () => {
  1147. const source = vi.fn()
  1148. const Comp = defineComponent({
  1149. render() {},
  1150. setup() {
  1151. watch(source, () => {})
  1152. },
  1153. })
  1154. const root = nodeOps.createElement('div')
  1155. createApp(Comp).mount(root)
  1156. // should not have any arguments
  1157. expect(source.mock.calls[0]).toMatchObject([])
  1158. })
  1159. // #2728
  1160. test('pre watcher callbacks should not track dependencies', async () => {
  1161. const a = ref(0)
  1162. const b = ref(0)
  1163. const updated = vi.fn()
  1164. const Child = defineComponent({
  1165. props: ['a'],
  1166. updated,
  1167. watch: {
  1168. a() {
  1169. b.value
  1170. },
  1171. },
  1172. render() {
  1173. return h('div', this.a)
  1174. },
  1175. })
  1176. const Parent = defineComponent({
  1177. render() {
  1178. return h(Child, { a: a.value })
  1179. },
  1180. })
  1181. const root = nodeOps.createElement('div')
  1182. createApp(Parent).mount(root)
  1183. a.value++
  1184. await nextTick()
  1185. expect(updated).toHaveBeenCalledTimes(1)
  1186. b.value++
  1187. await nextTick()
  1188. // should not track b as dependency of Child
  1189. expect(updated).toHaveBeenCalledTimes(1)
  1190. })
  1191. test('watching keypath', async () => {
  1192. const spy = vi.fn()
  1193. const Comp = defineComponent({
  1194. render() {},
  1195. data() {
  1196. return {
  1197. a: {
  1198. b: 1,
  1199. },
  1200. }
  1201. },
  1202. watch: {
  1203. 'a.b': spy,
  1204. },
  1205. created(this: any) {
  1206. this.$watch('a.b', spy)
  1207. },
  1208. mounted(this: any) {
  1209. this.a.b++
  1210. },
  1211. })
  1212. const root = nodeOps.createElement('div')
  1213. createApp(Comp).mount(root)
  1214. await nextTick()
  1215. expect(spy).toHaveBeenCalledTimes(2)
  1216. })
  1217. it('watching sources: ref<any[]>', async () => {
  1218. const foo = ref([1])
  1219. const spy = vi.fn()
  1220. watch(foo, () => {
  1221. spy()
  1222. })
  1223. foo.value = foo.value.slice()
  1224. await nextTick()
  1225. expect(spy).toBeCalledTimes(1)
  1226. })
  1227. it('watching multiple sources: computed', async () => {
  1228. let count = 0
  1229. const value = ref('1')
  1230. const plus = computed(() => !!value.value)
  1231. watch([plus], () => {
  1232. count++
  1233. })
  1234. value.value = '2'
  1235. await nextTick()
  1236. expect(plus.value).toBe(true)
  1237. expect(count).toBe(0)
  1238. })
  1239. // #4158
  1240. test('watch should not register in owner component if created inside detached scope', () => {
  1241. let instance: ComponentInternalInstance
  1242. const Comp = {
  1243. setup() {
  1244. instance = getCurrentInstance()!
  1245. effectScope(true).run(() => {
  1246. watch(
  1247. () => 1,
  1248. () => {},
  1249. )
  1250. })
  1251. return () => ''
  1252. },
  1253. }
  1254. const root = nodeOps.createElement('div')
  1255. createApp(Comp).mount(root)
  1256. // should not record watcher in detached scope and only the instance's
  1257. // own update effect
  1258. expect(instance!.scope.effects.length).toBe(1)
  1259. })
  1260. test('watchEffect should keep running if created in a detached scope', async () => {
  1261. const trigger = ref(0)
  1262. let countWE = 0
  1263. let countW = 0
  1264. const Comp = {
  1265. setup() {
  1266. effectScope(true).run(() => {
  1267. watchEffect(() => {
  1268. trigger.value
  1269. countWE++
  1270. })
  1271. watch(trigger, () => countW++)
  1272. })
  1273. return () => ''
  1274. },
  1275. }
  1276. const root = nodeOps.createElement('div')
  1277. render(h(Comp), root)
  1278. // only watchEffect as ran so far
  1279. expect(countWE).toBe(1)
  1280. expect(countW).toBe(0)
  1281. trigger.value++
  1282. await nextTick()
  1283. // both watchers run while component is mounted
  1284. expect(countWE).toBe(2)
  1285. expect(countW).toBe(1)
  1286. render(null, root) // unmount
  1287. await nextTick()
  1288. trigger.value++
  1289. await nextTick()
  1290. // both watchers run again event though component has been unmounted
  1291. expect(countWE).toBe(3)
  1292. expect(countW).toBe(2)
  1293. })
  1294. const options = [
  1295. { name: 'only trigger once watch' },
  1296. {
  1297. deep: true,
  1298. name: 'only trigger once watch with deep',
  1299. },
  1300. {
  1301. flush: 'sync',
  1302. name: 'only trigger once watch with flush: sync',
  1303. },
  1304. {
  1305. flush: 'pre',
  1306. name: 'only trigger once watch with flush: pre',
  1307. },
  1308. {
  1309. immediate: true,
  1310. name: 'only trigger once watch with immediate',
  1311. },
  1312. ] as const
  1313. test.each(options)('$name', async option => {
  1314. const count = ref(0)
  1315. const cb = vi.fn()
  1316. watch(count, cb, { once: true, ...option })
  1317. count.value++
  1318. await nextTick()
  1319. expect(count.value).toBe(1)
  1320. expect(cb).toHaveBeenCalledTimes(1)
  1321. count.value++
  1322. await nextTick()
  1323. expect(count.value).toBe(2)
  1324. expect(cb).toHaveBeenCalledTimes(1)
  1325. })
  1326. // #5151
  1327. test('OnCleanup also needs to be cleaned,', async () => {
  1328. const spy1 = vi.fn()
  1329. const spy2 = vi.fn()
  1330. const num = ref(0)
  1331. watch(num, (value, oldValue, onCleanup) => {
  1332. if (value > 1) {
  1333. return
  1334. }
  1335. spy1()
  1336. onCleanup(() => {
  1337. // OnCleanup also needs to be cleaned
  1338. spy2()
  1339. })
  1340. })
  1341. num.value++
  1342. await nextTick()
  1343. expect(spy1).toHaveBeenCalledTimes(1)
  1344. expect(spy2).toHaveBeenCalledTimes(0)
  1345. num.value++
  1346. await nextTick()
  1347. expect(spy1).toHaveBeenCalledTimes(1)
  1348. expect(spy2).toHaveBeenCalledTimes(1)
  1349. num.value++
  1350. await nextTick()
  1351. // would not be calld when value>1
  1352. expect(spy1).toHaveBeenCalledTimes(1)
  1353. expect(spy2).toHaveBeenCalledTimes(1)
  1354. })
  1355. it('watching reactive depth', async () => {
  1356. const state = reactive({
  1357. a: {
  1358. b: {
  1359. c: {
  1360. d: {
  1361. e: 1,
  1362. },
  1363. },
  1364. },
  1365. },
  1366. })
  1367. const cb = vi.fn()
  1368. watch(state, cb, { deep: 2 })
  1369. state.a.b = { c: { d: { e: 2 } } }
  1370. await nextTick()
  1371. expect(cb).toHaveBeenCalledTimes(1)
  1372. state.a.b.c = { d: { e: 3 } }
  1373. await nextTick()
  1374. expect(cb).toHaveBeenCalledTimes(1)
  1375. state.a.b = { c: { d: { e: 4 } } }
  1376. await nextTick()
  1377. expect(cb).toHaveBeenCalledTimes(2)
  1378. })
  1379. it('watching ref depth', async () => {
  1380. const state = ref({
  1381. a: {
  1382. b: 2,
  1383. },
  1384. })
  1385. const cb = vi.fn()
  1386. watch(state, cb, { deep: 1 })
  1387. state.value.a.b = 3
  1388. await nextTick()
  1389. expect(cb).toHaveBeenCalledTimes(0)
  1390. state.value.a = { b: 3 }
  1391. await nextTick()
  1392. expect(cb).toHaveBeenCalledTimes(1)
  1393. })
  1394. it('watching array depth', async () => {
  1395. const arr = ref([
  1396. {
  1397. a: {
  1398. b: 2,
  1399. },
  1400. },
  1401. {
  1402. a: {
  1403. b: 3,
  1404. },
  1405. },
  1406. ])
  1407. const cb = vi.fn()
  1408. watch(arr, cb, { deep: 2 })
  1409. arr.value[0].a.b = 3
  1410. await nextTick()
  1411. expect(cb).toHaveBeenCalledTimes(0)
  1412. arr.value[0].a = { b: 3 }
  1413. await nextTick()
  1414. expect(cb).toHaveBeenCalledTimes(1)
  1415. arr.value[1].a = { b: 4 }
  1416. await nextTick()
  1417. expect(cb).toHaveBeenCalledTimes(2)
  1418. arr.value.push({ a: { b: 5 } })
  1419. await nextTick()
  1420. expect(cb).toHaveBeenCalledTimes(3)
  1421. arr.value.pop()
  1422. await nextTick()
  1423. expect(cb).toHaveBeenCalledTimes(4)
  1424. })
  1425. test('pause / resume', async () => {
  1426. const count = ref(0)
  1427. const cb = vi.fn()
  1428. const { pause, resume } = watch(count, cb)
  1429. count.value++
  1430. await nextTick()
  1431. expect(cb).toHaveBeenCalledTimes(1)
  1432. expect(cb).toHaveBeenLastCalledWith(1, 0, expect.any(Function))
  1433. pause()
  1434. count.value++
  1435. await nextTick()
  1436. expect(cb).toHaveBeenCalledTimes(1)
  1437. expect(cb).toHaveBeenLastCalledWith(1, 0, expect.any(Function))
  1438. resume()
  1439. count.value++
  1440. await nextTick()
  1441. expect(cb).toHaveBeenCalledTimes(2)
  1442. expect(cb).toHaveBeenLastCalledWith(3, 1, expect.any(Function))
  1443. count.value++
  1444. await nextTick()
  1445. expect(cb).toHaveBeenCalledTimes(3)
  1446. expect(cb).toHaveBeenLastCalledWith(4, 3, expect.any(Function))
  1447. pause()
  1448. count.value++
  1449. await nextTick()
  1450. expect(cb).toHaveBeenCalledTimes(3)
  1451. expect(cb).toHaveBeenLastCalledWith(4, 3, expect.any(Function))
  1452. resume()
  1453. await nextTick()
  1454. expect(cb).toHaveBeenCalledTimes(4)
  1455. expect(cb).toHaveBeenLastCalledWith(5, 4, expect.any(Function))
  1456. })
  1457. it('shallowReactive', async () => {
  1458. const state = shallowReactive({
  1459. msg: ref('hello'),
  1460. foo: {
  1461. a: ref(1),
  1462. b: 2,
  1463. },
  1464. bar: 'bar',
  1465. })
  1466. const spy = vi.fn()
  1467. watch(state, spy)
  1468. state.msg.value = 'hi'
  1469. await nextTick()
  1470. expect(spy).not.toHaveBeenCalled()
  1471. state.bar = 'bar2'
  1472. await nextTick()
  1473. expect(spy).toHaveBeenCalledTimes(1)
  1474. state.foo.a.value++
  1475. state.foo.b++
  1476. await nextTick()
  1477. expect(spy).toHaveBeenCalledTimes(1)
  1478. state.bar = 'bar3'
  1479. await nextTick()
  1480. expect(spy).toHaveBeenCalledTimes(2)
  1481. })
  1482. it('watching reactive with deep: false', async () => {
  1483. const state = reactive({
  1484. foo: {
  1485. a: 2,
  1486. },
  1487. bar: 'bar',
  1488. })
  1489. const spy = vi.fn()
  1490. watch(state, spy, { deep: false })
  1491. state.foo.a++
  1492. await nextTick()
  1493. expect(spy).toHaveBeenCalledTimes(0)
  1494. state.bar = 'bar2'
  1495. await nextTick()
  1496. expect(spy).toHaveBeenCalledTimes(1)
  1497. })
  1498. test("effect should be removed from scope's effects after it is stopped", () => {
  1499. const num = ref(0)
  1500. let unwatch: () => void
  1501. let instance: ComponentInternalInstance
  1502. const Comp = {
  1503. setup() {
  1504. instance = getCurrentInstance()!
  1505. unwatch = watch(num, () => {
  1506. console.log(num.value)
  1507. })
  1508. return () => null
  1509. },
  1510. }
  1511. const root = nodeOps.createElement('div')
  1512. createApp(Comp).mount(root)
  1513. expect(instance!.scope.effects.length).toBe(2)
  1514. unwatch!()
  1515. expect(instance!.scope.effects.length).toBe(1)
  1516. const scope = effectScope()
  1517. scope.run(() => {
  1518. unwatch = watch(num, () => {
  1519. console.log(num.value)
  1520. })
  1521. })
  1522. expect(scope.effects.length).toBe(1)
  1523. unwatch!()
  1524. expect(scope.effects.length).toBe(0)
  1525. })
  1526. // simplified case of VueUse syncRef
  1527. test('sync watcher should not be batched', () => {
  1528. const a = ref(0)
  1529. const b = ref(0)
  1530. let pauseB = false
  1531. watch(
  1532. a,
  1533. () => {
  1534. pauseB = true
  1535. b.value = a.value + 1
  1536. pauseB = false
  1537. },
  1538. { flush: 'sync' },
  1539. )
  1540. watch(
  1541. b,
  1542. () => {
  1543. if (!pauseB) {
  1544. throw new Error('should not be called')
  1545. }
  1546. },
  1547. { flush: 'sync' },
  1548. )
  1549. a.value = 1
  1550. expect(b.value).toBe(2)
  1551. })
  1552. test('watchEffect should not fire on computed deps that did not change', async () => {
  1553. const a = ref(0)
  1554. const c = computed(() => a.value % 2)
  1555. const spy = vi.fn()
  1556. watchEffect(() => {
  1557. spy()
  1558. c.value
  1559. })
  1560. expect(spy).toHaveBeenCalledTimes(1)
  1561. a.value += 2
  1562. await nextTick()
  1563. expect(spy).toHaveBeenCalledTimes(1)
  1564. })
  1565. test('circular reference', async () => {
  1566. const obj = { a: 1 }
  1567. // @ts-expect-error
  1568. obj.b = obj
  1569. const foo = ref(obj)
  1570. const spy = vi.fn()
  1571. watch(foo, spy, { deep: true })
  1572. // @ts-expect-error
  1573. foo.value.b.a = 2
  1574. await nextTick()
  1575. expect(spy).toHaveBeenCalledTimes(1)
  1576. expect(foo.value.a).toBe(2)
  1577. })
  1578. test('watch immediate error in effect scope should be catched by onErrorCaptured', async () => {
  1579. const warn = vi.spyOn(console, 'warn')
  1580. warn.mockImplementation(() => {})
  1581. const ERROR_IN_SCOPE = 'ERROR_IN_SCOPE'
  1582. const ERROR_OUT_SCOPE = 'ERROR_OUT_SCOPE'
  1583. const errors = ref<string[]>([])
  1584. const Comp = {
  1585. setup() {
  1586. const trigger = ref(0)
  1587. effectScope(true).run(() => {
  1588. watch(
  1589. trigger,
  1590. () => {
  1591. throw new Error(ERROR_IN_SCOPE)
  1592. },
  1593. { immediate: true },
  1594. )
  1595. })
  1596. watchEffect(() => {
  1597. throw new Error(ERROR_OUT_SCOPE)
  1598. })
  1599. return () => ''
  1600. },
  1601. }
  1602. const root = nodeOps.createElement('div')
  1603. render(
  1604. h(
  1605. {
  1606. setup(_, { slots }) {
  1607. onErrorCaptured(e => {
  1608. errors.value.push(e.message)
  1609. return false
  1610. })
  1611. return () => h('div', slots.default && slots.default())
  1612. },
  1613. },
  1614. null,
  1615. () => [h(Comp)],
  1616. ),
  1617. root,
  1618. )
  1619. await nextTick()
  1620. // only watchEffect as ran so far
  1621. expect(errors.value).toHaveLength(2)
  1622. expect(errors.value[0]).toBe(ERROR_IN_SCOPE)
  1623. expect(errors.value[1]).toBe(ERROR_OUT_SCOPE)
  1624. warn.mockRestore()
  1625. })
  1626. })