apiWatch.spec.ts 45 KB

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