apiWatch.spec.ts 48 KB

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