apiWatch.spec.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064
  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. ITERATE_KEY,
  29. type Ref,
  30. type ShallowRef,
  31. TrackOpTypes,
  32. TriggerOpTypes,
  33. effectScope,
  34. onScopeDispose,
  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('should not leak `this.proxy` to setup()', () => {
  1209. const source = vi.fn()
  1210. const Comp = defineComponent({
  1211. render() {},
  1212. setup() {
  1213. watch(source, () => {})
  1214. },
  1215. })
  1216. const root = nodeOps.createElement('div')
  1217. createApp(Comp).mount(root)
  1218. // should not have any arguments
  1219. expect(source.mock.calls[0]).toMatchObject([])
  1220. })
  1221. // #2728
  1222. test('pre watcher callbacks should not track dependencies', async () => {
  1223. const a = ref(0)
  1224. const b = ref(0)
  1225. const updated = vi.fn()
  1226. const Child = defineComponent({
  1227. props: ['a'],
  1228. updated,
  1229. watch: {
  1230. a() {
  1231. b.value
  1232. },
  1233. },
  1234. render() {
  1235. return h('div', this.a)
  1236. },
  1237. })
  1238. const Parent = defineComponent({
  1239. render() {
  1240. return h(Child, { a: a.value })
  1241. },
  1242. })
  1243. const root = nodeOps.createElement('div')
  1244. createApp(Parent).mount(root)
  1245. a.value++
  1246. await nextTick()
  1247. expect(updated).toHaveBeenCalledTimes(1)
  1248. b.value++
  1249. await nextTick()
  1250. // should not track b as dependency of Child
  1251. expect(updated).toHaveBeenCalledTimes(1)
  1252. })
  1253. test('watching keypath', async () => {
  1254. const spy = vi.fn()
  1255. const Comp = defineComponent({
  1256. render() {},
  1257. data() {
  1258. return {
  1259. a: {
  1260. b: 1,
  1261. },
  1262. }
  1263. },
  1264. watch: {
  1265. 'a.b': spy,
  1266. },
  1267. created(this: any) {
  1268. this.$watch('a.b', spy)
  1269. },
  1270. mounted(this: any) {
  1271. this.a.b++
  1272. },
  1273. })
  1274. const root = nodeOps.createElement('div')
  1275. createApp(Comp).mount(root)
  1276. await nextTick()
  1277. expect(spy).toHaveBeenCalledTimes(2)
  1278. })
  1279. it('watching sources: ref<any[]>', async () => {
  1280. const foo = ref([1])
  1281. const spy = vi.fn()
  1282. watch(foo, () => {
  1283. spy()
  1284. })
  1285. foo.value = foo.value.slice()
  1286. await nextTick()
  1287. expect(spy).toBeCalledTimes(1)
  1288. })
  1289. it('watching multiple sources: computed', async () => {
  1290. let count = 0
  1291. const value = ref('1')
  1292. const plus = computed(() => !!value.value)
  1293. watch([plus], () => {
  1294. count++
  1295. })
  1296. value.value = '2'
  1297. await nextTick()
  1298. expect(plus.value).toBe(true)
  1299. expect(count).toBe(0)
  1300. })
  1301. // #4158
  1302. test('watch should not register in owner component if created inside detached scope', () => {
  1303. let instance: ComponentInternalInstance
  1304. const Comp = {
  1305. setup() {
  1306. instance = getCurrentInstance()!
  1307. effectScope(true).run(() => {
  1308. watch(
  1309. () => 1,
  1310. () => {},
  1311. )
  1312. })
  1313. return () => ''
  1314. },
  1315. }
  1316. const root = nodeOps.createElement('div')
  1317. createApp(Comp).mount(root)
  1318. // should not record watcher in detached scope and only the instance's
  1319. // own update effect
  1320. expect(instance!.scope.effects.length).toBe(1)
  1321. })
  1322. test('watchEffect should keep running if created in a detached scope', async () => {
  1323. const trigger = ref(0)
  1324. let countWE = 0
  1325. let countW = 0
  1326. const Comp = {
  1327. setup() {
  1328. effectScope(true).run(() => {
  1329. watchEffect(() => {
  1330. trigger.value
  1331. countWE++
  1332. })
  1333. watch(trigger, () => countW++)
  1334. })
  1335. return () => ''
  1336. },
  1337. }
  1338. const root = nodeOps.createElement('div')
  1339. render(h(Comp), root)
  1340. // only watchEffect as ran so far
  1341. expect(countWE).toBe(1)
  1342. expect(countW).toBe(0)
  1343. trigger.value++
  1344. await nextTick()
  1345. // both watchers run while component is mounted
  1346. expect(countWE).toBe(2)
  1347. expect(countW).toBe(1)
  1348. render(null, root) // unmount
  1349. await nextTick()
  1350. trigger.value++
  1351. await nextTick()
  1352. // both watchers run again event though component has been unmounted
  1353. expect(countWE).toBe(3)
  1354. expect(countW).toBe(2)
  1355. })
  1356. const options = [
  1357. { name: 'only trigger once watch' },
  1358. {
  1359. deep: true,
  1360. name: 'only trigger once watch with deep',
  1361. },
  1362. {
  1363. flush: 'sync',
  1364. name: 'only trigger once watch with flush: sync',
  1365. },
  1366. {
  1367. flush: 'pre',
  1368. name: 'only trigger once watch with flush: pre',
  1369. },
  1370. {
  1371. immediate: true,
  1372. name: 'only trigger once watch with immediate',
  1373. },
  1374. ] as const
  1375. test.each(options)('$name', async option => {
  1376. const count = ref(0)
  1377. const cb = vi.fn()
  1378. watch(count, cb, { once: true, ...option })
  1379. count.value++
  1380. await nextTick()
  1381. expect(count.value).toBe(1)
  1382. expect(cb).toHaveBeenCalledTimes(1)
  1383. count.value++
  1384. await nextTick()
  1385. expect(count.value).toBe(2)
  1386. expect(cb).toHaveBeenCalledTimes(1)
  1387. })
  1388. // #5151
  1389. test('OnCleanup also needs to be cleaned,', async () => {
  1390. const spy1 = vi.fn()
  1391. const spy2 = vi.fn()
  1392. const num = ref(0)
  1393. watch(num, (value, oldValue, onCleanup) => {
  1394. if (value > 1) {
  1395. return
  1396. }
  1397. spy1()
  1398. onCleanup(() => {
  1399. // OnCleanup also needs to be cleaned
  1400. spy2()
  1401. })
  1402. })
  1403. num.value++
  1404. await nextTick()
  1405. expect(spy1).toHaveBeenCalledTimes(1)
  1406. expect(spy2).toHaveBeenCalledTimes(0)
  1407. num.value++
  1408. await nextTick()
  1409. expect(spy1).toHaveBeenCalledTimes(1)
  1410. expect(spy2).toHaveBeenCalledTimes(1)
  1411. num.value++
  1412. await nextTick()
  1413. // would not be called when value>1
  1414. expect(spy1).toHaveBeenCalledTimes(1)
  1415. expect(spy2).toHaveBeenCalledTimes(1)
  1416. })
  1417. it('watching reactive depth', async () => {
  1418. const state = reactive({
  1419. a: {
  1420. b: {
  1421. c: {
  1422. d: {
  1423. e: 1,
  1424. },
  1425. },
  1426. },
  1427. },
  1428. })
  1429. const cb = vi.fn()
  1430. watch(state, cb, { deep: 2 })
  1431. state.a.b = { c: { d: { e: 2 } } }
  1432. await nextTick()
  1433. expect(cb).toHaveBeenCalledTimes(1)
  1434. state.a.b.c = { d: { e: 3 } }
  1435. await nextTick()
  1436. expect(cb).toHaveBeenCalledTimes(1)
  1437. state.a.b = { c: { d: { e: 4 } } }
  1438. await nextTick()
  1439. expect(cb).toHaveBeenCalledTimes(2)
  1440. })
  1441. it('watching ref depth', async () => {
  1442. const state = ref({
  1443. a: {
  1444. b: 2,
  1445. },
  1446. })
  1447. const cb = vi.fn()
  1448. watch(state, cb, { deep: 1 })
  1449. state.value.a.b = 3
  1450. await nextTick()
  1451. expect(cb).toHaveBeenCalledTimes(0)
  1452. state.value.a = { b: 3 }
  1453. await nextTick()
  1454. expect(cb).toHaveBeenCalledTimes(1)
  1455. })
  1456. it('watching array depth', async () => {
  1457. const arr = ref([
  1458. {
  1459. a: {
  1460. b: 2,
  1461. },
  1462. },
  1463. {
  1464. a: {
  1465. b: 3,
  1466. },
  1467. },
  1468. ])
  1469. const cb = vi.fn()
  1470. watch(arr, cb, { deep: 2 })
  1471. arr.value[0].a.b = 3
  1472. await nextTick()
  1473. expect(cb).toHaveBeenCalledTimes(0)
  1474. arr.value[0].a = { b: 3 }
  1475. await nextTick()
  1476. expect(cb).toHaveBeenCalledTimes(1)
  1477. arr.value[1].a = { b: 4 }
  1478. await nextTick()
  1479. expect(cb).toHaveBeenCalledTimes(2)
  1480. arr.value.push({ a: { b: 5 } })
  1481. await nextTick()
  1482. expect(cb).toHaveBeenCalledTimes(3)
  1483. arr.value.pop()
  1484. await nextTick()
  1485. expect(cb).toHaveBeenCalledTimes(4)
  1486. })
  1487. test('watching the same object at different depths', async () => {
  1488. const arr1: any[] = reactive([[[{ foo: {} }]]])
  1489. const arr2 = arr1[0]
  1490. const arr3 = arr2[0]
  1491. const obj = arr3[0]
  1492. arr1.push(arr3)
  1493. const cb1 = vi.fn()
  1494. const cb2 = vi.fn()
  1495. const cb3 = vi.fn()
  1496. const cb4 = vi.fn()
  1497. watch(arr1, cb1, { deep: 1 })
  1498. watch(arr1, cb2, { deep: 2 })
  1499. watch(arr1, cb3, { deep: 3 })
  1500. watch(arr1, cb4, { deep: 4 })
  1501. await nextTick()
  1502. expect(cb1).toHaveBeenCalledTimes(0)
  1503. expect(cb2).toHaveBeenCalledTimes(0)
  1504. expect(cb3).toHaveBeenCalledTimes(0)
  1505. expect(cb4).toHaveBeenCalledTimes(0)
  1506. obj.foo = {}
  1507. await nextTick()
  1508. expect(cb1).toHaveBeenCalledTimes(0)
  1509. expect(cb2).toHaveBeenCalledTimes(0)
  1510. expect(cb3).toHaveBeenCalledTimes(1)
  1511. expect(cb4).toHaveBeenCalledTimes(1)
  1512. obj.foo.bar = 1
  1513. await nextTick()
  1514. expect(cb1).toHaveBeenCalledTimes(0)
  1515. expect(cb2).toHaveBeenCalledTimes(0)
  1516. expect(cb3).toHaveBeenCalledTimes(1)
  1517. expect(cb4).toHaveBeenCalledTimes(2)
  1518. arr3.push(obj.foo)
  1519. await nextTick()
  1520. expect(cb1).toHaveBeenCalledTimes(0)
  1521. expect(cb2).toHaveBeenCalledTimes(1)
  1522. expect(cb3).toHaveBeenCalledTimes(2)
  1523. expect(cb4).toHaveBeenCalledTimes(3)
  1524. obj.foo.bar = 2
  1525. await nextTick()
  1526. expect(cb1).toHaveBeenCalledTimes(0)
  1527. expect(cb2).toHaveBeenCalledTimes(1)
  1528. expect(cb3).toHaveBeenCalledTimes(3)
  1529. expect(cb4).toHaveBeenCalledTimes(4)
  1530. })
  1531. test('pause / resume', async () => {
  1532. const count = ref(0)
  1533. const cb = vi.fn()
  1534. const { pause, resume } = watch(count, cb)
  1535. count.value++
  1536. await nextTick()
  1537. expect(cb).toHaveBeenCalledTimes(1)
  1538. expect(cb).toHaveBeenLastCalledWith(1, 0, expect.any(Function))
  1539. pause()
  1540. count.value++
  1541. await nextTick()
  1542. expect(cb).toHaveBeenCalledTimes(1)
  1543. expect(cb).toHaveBeenLastCalledWith(1, 0, expect.any(Function))
  1544. resume()
  1545. count.value++
  1546. await nextTick()
  1547. expect(cb).toHaveBeenCalledTimes(2)
  1548. expect(cb).toHaveBeenLastCalledWith(3, 1, expect.any(Function))
  1549. count.value++
  1550. await nextTick()
  1551. expect(cb).toHaveBeenCalledTimes(3)
  1552. expect(cb).toHaveBeenLastCalledWith(4, 3, expect.any(Function))
  1553. pause()
  1554. count.value++
  1555. await nextTick()
  1556. expect(cb).toHaveBeenCalledTimes(3)
  1557. expect(cb).toHaveBeenLastCalledWith(4, 3, expect.any(Function))
  1558. resume()
  1559. await nextTick()
  1560. expect(cb).toHaveBeenCalledTimes(4)
  1561. expect(cb).toHaveBeenLastCalledWith(5, 4, expect.any(Function))
  1562. })
  1563. it('shallowReactive', async () => {
  1564. const state = shallowReactive({
  1565. msg: ref('hello'),
  1566. foo: {
  1567. a: ref(1),
  1568. b: 2,
  1569. },
  1570. bar: 'bar',
  1571. })
  1572. const spy = vi.fn()
  1573. watch(state, spy)
  1574. state.msg.value = 'hi'
  1575. await nextTick()
  1576. expect(spy).not.toHaveBeenCalled()
  1577. state.bar = 'bar2'
  1578. await nextTick()
  1579. expect(spy).toHaveBeenCalledTimes(1)
  1580. state.foo.a.value++
  1581. state.foo.b++
  1582. await nextTick()
  1583. expect(spy).toHaveBeenCalledTimes(1)
  1584. state.bar = 'bar3'
  1585. await nextTick()
  1586. expect(spy).toHaveBeenCalledTimes(2)
  1587. })
  1588. it('watching reactive with deep: false', async () => {
  1589. const state = reactive({
  1590. foo: {
  1591. a: 2,
  1592. },
  1593. bar: 'bar',
  1594. })
  1595. const spy = vi.fn()
  1596. watch(state, spy, { deep: false })
  1597. state.foo.a++
  1598. await nextTick()
  1599. expect(spy).toHaveBeenCalledTimes(0)
  1600. state.bar = 'bar2'
  1601. await nextTick()
  1602. expect(spy).toHaveBeenCalledTimes(1)
  1603. })
  1604. test("effect should be removed from scope's effects after it is stopped", () => {
  1605. const num = ref(0)
  1606. let unwatch: () => void
  1607. let instance: ComponentInternalInstance
  1608. const Comp = {
  1609. setup() {
  1610. instance = getCurrentInstance()!
  1611. unwatch = watch(num, () => {
  1612. console.log(num.value)
  1613. })
  1614. return () => null
  1615. },
  1616. }
  1617. const root = nodeOps.createElement('div')
  1618. createApp(Comp).mount(root)
  1619. expect(instance!.scope.effects.length).toBe(2)
  1620. unwatch!()
  1621. expect(instance!.scope.effects.length).toBe(1)
  1622. const scope = effectScope()
  1623. scope.run(() => {
  1624. unwatch = watch(num, () => {
  1625. console.log(num.value)
  1626. })
  1627. })
  1628. expect(scope.effects.length).toBe(1)
  1629. unwatch!()
  1630. expect(scope.effects.length).toBe(0)
  1631. scope.run(() => {
  1632. watch(num, () => {}, { once: true, immediate: true })
  1633. })
  1634. expect(scope.effects.length).toBe(0)
  1635. })
  1636. // simplified case of VueUse syncRef
  1637. test('sync watcher should not be batched', () => {
  1638. const a = ref(0)
  1639. const b = ref(0)
  1640. let pauseB = false
  1641. watch(
  1642. a,
  1643. () => {
  1644. pauseB = true
  1645. b.value = a.value + 1
  1646. pauseB = false
  1647. },
  1648. { flush: 'sync' },
  1649. )
  1650. watch(
  1651. b,
  1652. () => {
  1653. if (!pauseB) {
  1654. throw new Error('should not be called')
  1655. }
  1656. },
  1657. { flush: 'sync' },
  1658. )
  1659. a.value = 1
  1660. expect(b.value).toBe(2)
  1661. })
  1662. test('watchEffect should not fire on computed deps that did not change', async () => {
  1663. const a = ref(0)
  1664. const c = computed(() => a.value % 2)
  1665. const spy = vi.fn()
  1666. watchEffect(() => {
  1667. spy()
  1668. c.value
  1669. })
  1670. expect(spy).toHaveBeenCalledTimes(1)
  1671. a.value += 2
  1672. await nextTick()
  1673. expect(spy).toHaveBeenCalledTimes(1)
  1674. })
  1675. test('circular reference', async () => {
  1676. const obj = { a: 1 }
  1677. // @ts-expect-error
  1678. obj.b = obj
  1679. const foo = ref(obj)
  1680. const spy = vi.fn()
  1681. watch(foo, spy, { deep: true })
  1682. // @ts-expect-error
  1683. foo.value.b.a = 2
  1684. await nextTick()
  1685. expect(spy).toHaveBeenCalledTimes(1)
  1686. expect(foo.value.a).toBe(2)
  1687. })
  1688. test('watch immediate error in effect scope should be caught by onErrorCaptured', async () => {
  1689. const warn = vi.spyOn(console, 'warn')
  1690. warn.mockImplementation(() => {})
  1691. const ERROR_IN_SCOPE = 'ERROR_IN_SCOPE'
  1692. const ERROR_OUT_SCOPE = 'ERROR_OUT_SCOPE'
  1693. const errors = ref<string[]>([])
  1694. const Comp = {
  1695. setup() {
  1696. const trigger = ref(0)
  1697. effectScope(true).run(() => {
  1698. watch(
  1699. trigger,
  1700. () => {
  1701. throw new Error(ERROR_IN_SCOPE)
  1702. },
  1703. { immediate: true },
  1704. )
  1705. })
  1706. watchEffect(() => {
  1707. throw new Error(ERROR_OUT_SCOPE)
  1708. })
  1709. return () => ''
  1710. },
  1711. }
  1712. const root = nodeOps.createElement('div')
  1713. render(
  1714. h(
  1715. {
  1716. setup(_, { slots }) {
  1717. onErrorCaptured(e => {
  1718. errors.value.push(e.message)
  1719. return false
  1720. })
  1721. return () => h('div', slots.default && slots.default())
  1722. },
  1723. },
  1724. null,
  1725. () => [h(Comp)],
  1726. ),
  1727. root,
  1728. )
  1729. await nextTick()
  1730. // only watchEffect as ran so far
  1731. expect(errors.value).toHaveLength(2)
  1732. expect(errors.value[0]).toBe(ERROR_IN_SCOPE)
  1733. expect(errors.value[1]).toBe(ERROR_OUT_SCOPE)
  1734. warn.mockRestore()
  1735. })
  1736. test('should be executed correctly', () => {
  1737. const v = ref(1)
  1738. let foo = ''
  1739. watch(
  1740. v,
  1741. () => {
  1742. foo += '1'
  1743. },
  1744. {
  1745. flush: 'sync',
  1746. },
  1747. )
  1748. watch(
  1749. v,
  1750. () => {
  1751. foo += '2'
  1752. },
  1753. {
  1754. flush: 'sync',
  1755. },
  1756. )
  1757. expect(foo).toBe('')
  1758. v.value++
  1759. expect(foo).toBe('12')
  1760. })
  1761. // 12045
  1762. test('sync watcher should not break pre watchers', async () => {
  1763. const count1 = ref(0)
  1764. const count2 = ref(0)
  1765. watch(
  1766. count1,
  1767. () => {
  1768. count2.value++
  1769. },
  1770. { flush: 'sync' },
  1771. )
  1772. const spy1 = vi.fn()
  1773. watch([count1, count2], spy1)
  1774. const spy2 = vi.fn()
  1775. watch(count1, spy2)
  1776. count1.value++
  1777. await nextTick()
  1778. expect(spy1).toHaveBeenCalled()
  1779. expect(spy2).toHaveBeenCalled()
  1780. })
  1781. // #12631
  1782. test('this.$watch w/ onScopeDispose', () => {
  1783. const onCleanup = vi.fn()
  1784. const toggle = ref(true)
  1785. const Comp = defineComponent({
  1786. render() {},
  1787. created(this: any) {
  1788. this.$watch(
  1789. () => 1,
  1790. function () {},
  1791. )
  1792. onScopeDispose(onCleanup)
  1793. },
  1794. })
  1795. const App = defineComponent({
  1796. render() {
  1797. return toggle.value ? h(Comp) : null
  1798. },
  1799. })
  1800. const root = nodeOps.createElement('div')
  1801. createApp(App).mount(root)
  1802. expect(onCleanup).toBeCalledTimes(0)
  1803. })
  1804. })