apiWatch.spec.ts 36 KB

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