apiWatch.spec.ts 48 KB

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