apiWatch.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. import {
  2. watch,
  3. watchEffect,
  4. reactive,
  5. computed,
  6. nextTick,
  7. ref,
  8. h
  9. } from '../src/index'
  10. import { render, nodeOps, serializeInner, TestElement } from '@vue/runtime-test'
  11. import {
  12. ITERATE_KEY,
  13. DebuggerEvent,
  14. TrackOpTypes,
  15. TriggerOpTypes,
  16. triggerRef
  17. } from '@vue/reactivity'
  18. // reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
  19. describe('api: watch', () => {
  20. it('effect', async () => {
  21. const state = reactive({ count: 0 })
  22. let dummy
  23. watchEffect(() => {
  24. dummy = state.count
  25. })
  26. expect(dummy).toBe(0)
  27. state.count++
  28. await nextTick()
  29. expect(dummy).toBe(1)
  30. })
  31. it('watching single source: getter', async () => {
  32. const state = reactive({ count: 0 })
  33. let dummy
  34. watch(
  35. () => state.count,
  36. (count, prevCount) => {
  37. dummy = [count, prevCount]
  38. // assert types
  39. count + 1
  40. if (prevCount) {
  41. prevCount + 1
  42. }
  43. }
  44. )
  45. state.count++
  46. await nextTick()
  47. expect(dummy).toMatchObject([1, 0])
  48. })
  49. it('watching single source: ref', async () => {
  50. const count = ref(0)
  51. let dummy
  52. watch(count, (count, prevCount) => {
  53. dummy = [count, prevCount]
  54. // assert types
  55. count + 1
  56. if (prevCount) {
  57. prevCount + 1
  58. }
  59. })
  60. count.value++
  61. await nextTick()
  62. expect(dummy).toMatchObject([1, 0])
  63. })
  64. it('watching single source: array', async () => {
  65. const array = reactive([] as number[])
  66. const spy = jest.fn()
  67. watch(array, spy)
  68. array.push(1)
  69. await nextTick()
  70. expect(spy).toBeCalledTimes(1)
  71. expect(spy).toBeCalledWith([1], expect.anything(), expect.anything())
  72. })
  73. it('should not fire if watched getter result did not change', async () => {
  74. const spy = jest.fn()
  75. const n = ref(0)
  76. watch(() => n.value % 2, spy)
  77. n.value++
  78. await nextTick()
  79. expect(spy).toBeCalledTimes(1)
  80. n.value += 2
  81. await nextTick()
  82. // should not be called again because getter result did not change
  83. expect(spy).toBeCalledTimes(1)
  84. })
  85. it('watching single source: computed ref', async () => {
  86. const count = ref(0)
  87. const plus = computed(() => count.value + 1)
  88. let dummy
  89. watch(plus, (count, prevCount) => {
  90. dummy = [count, prevCount]
  91. // assert types
  92. count + 1
  93. if (prevCount) {
  94. prevCount + 1
  95. }
  96. })
  97. count.value++
  98. await nextTick()
  99. expect(dummy).toMatchObject([2, 1])
  100. })
  101. it('watching primitive with deep: true', async () => {
  102. const count = ref(0)
  103. let dummy
  104. watch(
  105. count,
  106. (c, prevCount) => {
  107. dummy = [c, prevCount]
  108. },
  109. {
  110. deep: true
  111. }
  112. )
  113. count.value++
  114. await nextTick()
  115. expect(dummy).toMatchObject([1, 0])
  116. })
  117. it('directly watching reactive object (with automatic deep: true)', async () => {
  118. const src = reactive({
  119. count: 0
  120. })
  121. let dummy
  122. watch(src, ({ count }) => {
  123. dummy = count
  124. })
  125. src.count++
  126. await nextTick()
  127. expect(dummy).toBe(1)
  128. })
  129. it('watching multiple sources', async () => {
  130. const state = reactive({ count: 1 })
  131. const count = ref(1)
  132. const plus = computed(() => count.value + 1)
  133. let dummy
  134. watch([() => state.count, count, plus], (vals, oldVals) => {
  135. dummy = [vals, oldVals]
  136. // assert types
  137. vals.concat(1)
  138. oldVals.concat(1)
  139. })
  140. state.count++
  141. count.value++
  142. await nextTick()
  143. expect(dummy).toMatchObject([[2, 2, 3], [1, 1, 2]])
  144. })
  145. it('watching multiple sources: readonly array', async () => {
  146. const state = reactive({ count: 1 })
  147. const status = ref(false)
  148. let dummy
  149. watch([() => state.count, status] as const, (vals, oldVals) => {
  150. dummy = [vals, oldVals]
  151. const [count] = vals
  152. const [, oldStatus] = oldVals
  153. // assert types
  154. count + 1
  155. oldStatus === true
  156. })
  157. state.count++
  158. status.value = true
  159. await nextTick()
  160. expect(dummy).toMatchObject([[2, true], [1, false]])
  161. })
  162. it('watching multiple sources: reactive object (with automatic deep: true)', async () => {
  163. const src = reactive({ count: 0 })
  164. let dummy
  165. watch([src], ([state]) => {
  166. dummy = state
  167. // assert types
  168. state.count === 1
  169. })
  170. src.count++
  171. await nextTick()
  172. expect(dummy).toMatchObject({ count: 1 })
  173. })
  174. it('warn invalid watch source', () => {
  175. // @ts-ignore
  176. watch(1, () => {})
  177. expect(`Invalid watch source`).toHaveBeenWarned()
  178. })
  179. it('warn invalid watch source: multiple sources', () => {
  180. watch([1], () => {})
  181. expect(`Invalid watch source`).toHaveBeenWarned()
  182. })
  183. it('stopping the watcher (effect)', async () => {
  184. const state = reactive({ count: 0 })
  185. let dummy
  186. const stop = watchEffect(() => {
  187. dummy = state.count
  188. })
  189. expect(dummy).toBe(0)
  190. stop()
  191. state.count++
  192. await nextTick()
  193. // should not update
  194. expect(dummy).toBe(0)
  195. })
  196. it('stopping the watcher (with source)', async () => {
  197. const state = reactive({ count: 0 })
  198. let dummy
  199. const stop = watch(
  200. () => state.count,
  201. count => {
  202. dummy = count
  203. }
  204. )
  205. state.count++
  206. await nextTick()
  207. expect(dummy).toBe(1)
  208. stop()
  209. state.count++
  210. await nextTick()
  211. // should not update
  212. expect(dummy).toBe(1)
  213. })
  214. it('cleanup registration (effect)', async () => {
  215. const state = reactive({ count: 0 })
  216. const cleanup = jest.fn()
  217. let dummy
  218. const stop = watchEffect(onCleanup => {
  219. onCleanup(cleanup)
  220. dummy = state.count
  221. })
  222. expect(dummy).toBe(0)
  223. state.count++
  224. await nextTick()
  225. expect(cleanup).toHaveBeenCalledTimes(1)
  226. expect(dummy).toBe(1)
  227. stop()
  228. expect(cleanup).toHaveBeenCalledTimes(2)
  229. })
  230. it('cleanup registration (with source)', async () => {
  231. const count = ref(0)
  232. const cleanup = jest.fn()
  233. let dummy
  234. const stop = watch(count, (count, prevCount, onCleanup) => {
  235. onCleanup(cleanup)
  236. dummy = count
  237. })
  238. count.value++
  239. await nextTick()
  240. expect(cleanup).toHaveBeenCalledTimes(0)
  241. expect(dummy).toBe(1)
  242. count.value++
  243. await nextTick()
  244. expect(cleanup).toHaveBeenCalledTimes(1)
  245. expect(dummy).toBe(2)
  246. stop()
  247. expect(cleanup).toHaveBeenCalledTimes(2)
  248. })
  249. it('flush timing: post (default)', async () => {
  250. const count = ref(0)
  251. let callCount = 0
  252. let result
  253. const assertion = jest.fn(count => {
  254. callCount++
  255. // on mount, the watcher callback should be called before DOM render
  256. // on update, should be called after the count is updated
  257. const expectedDOM = callCount === 1 ? `` : `${count}`
  258. result = serializeInner(root) === expectedDOM
  259. })
  260. const Comp = {
  261. setup() {
  262. watchEffect(() => {
  263. assertion(count.value)
  264. })
  265. return () => count.value
  266. }
  267. }
  268. const root = nodeOps.createElement('div')
  269. render(h(Comp), root)
  270. expect(assertion).toHaveBeenCalledTimes(1)
  271. expect(result).toBe(true)
  272. count.value++
  273. await nextTick()
  274. expect(assertion).toHaveBeenCalledTimes(2)
  275. expect(result).toBe(true)
  276. })
  277. it('flush timing: pre', async () => {
  278. const count = ref(0)
  279. const count2 = ref(0)
  280. let callCount = 0
  281. let result1
  282. let result2
  283. const assertion = jest.fn((count, count2Value) => {
  284. callCount++
  285. // on mount, the watcher callback should be called before DOM render
  286. // on update, should be called before the count is updated
  287. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  288. result1 = serializeInner(root) === expectedDOM
  289. // in a pre-flush callback, all state should have been updated
  290. const expectedState = callCount - 1
  291. result2 = count === expectedState && count2Value === expectedState
  292. })
  293. const Comp = {
  294. setup() {
  295. watchEffect(
  296. () => {
  297. assertion(count.value, count2.value)
  298. },
  299. {
  300. flush: 'pre'
  301. }
  302. )
  303. return () => count.value
  304. }
  305. }
  306. const root = nodeOps.createElement('div')
  307. render(h(Comp), root)
  308. expect(assertion).toHaveBeenCalledTimes(1)
  309. expect(result1).toBe(true)
  310. expect(result2).toBe(true)
  311. count.value++
  312. count2.value++
  313. await nextTick()
  314. // two mutations should result in 1 callback execution
  315. expect(assertion).toHaveBeenCalledTimes(2)
  316. expect(result1).toBe(true)
  317. expect(result2).toBe(true)
  318. })
  319. it('flush timing: sync', async () => {
  320. const count = ref(0)
  321. const count2 = ref(0)
  322. let callCount = 0
  323. let result1
  324. let result2
  325. const assertion = jest.fn(count => {
  326. callCount++
  327. // on mount, the watcher callback should be called before DOM render
  328. // on update, should be called before the count is updated
  329. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  330. result1 = serializeInner(root) === expectedDOM
  331. // in a sync callback, state mutation on the next line should not have
  332. // executed yet on the 2nd call, but will be on the 3rd call.
  333. const expectedState = callCount < 3 ? 0 : 1
  334. result2 = count2.value === expectedState
  335. })
  336. const Comp = {
  337. setup() {
  338. watchEffect(
  339. () => {
  340. assertion(count.value)
  341. },
  342. {
  343. flush: 'sync'
  344. }
  345. )
  346. return () => count.value
  347. }
  348. }
  349. const root = nodeOps.createElement('div')
  350. render(h(Comp), root)
  351. expect(assertion).toHaveBeenCalledTimes(1)
  352. expect(result1).toBe(true)
  353. expect(result2).toBe(true)
  354. count.value++
  355. count2.value++
  356. await nextTick()
  357. expect(assertion).toHaveBeenCalledTimes(3)
  358. expect(result1).toBe(true)
  359. expect(result2).toBe(true)
  360. })
  361. it('should not fire on component unmount w/ flush: post', async () => {
  362. const toggle = ref(true)
  363. const cb = jest.fn()
  364. const Comp = {
  365. setup() {
  366. watch(toggle, cb)
  367. },
  368. render() {}
  369. }
  370. const App = {
  371. render() {
  372. return toggle.value ? h(Comp) : null
  373. }
  374. }
  375. render(h(App), nodeOps.createElement('div'))
  376. expect(cb).not.toHaveBeenCalled()
  377. toggle.value = false
  378. await nextTick()
  379. expect(cb).not.toHaveBeenCalled()
  380. })
  381. it('should fire on component unmount w/ flush: pre', async () => {
  382. const toggle = ref(true)
  383. const cb = jest.fn()
  384. const Comp = {
  385. setup() {
  386. watch(toggle, cb, { flush: 'pre' })
  387. },
  388. render() {}
  389. }
  390. const App = {
  391. render() {
  392. return toggle.value ? h(Comp) : null
  393. }
  394. }
  395. render(h(App), nodeOps.createElement('div'))
  396. expect(cb).not.toHaveBeenCalled()
  397. toggle.value = false
  398. await nextTick()
  399. expect(cb).toHaveBeenCalledTimes(1)
  400. })
  401. // #1763
  402. it('flush: pre watcher watching props should fire before child update', async () => {
  403. const a = ref(0)
  404. const b = ref(0)
  405. const c = ref(0)
  406. const calls: string[] = []
  407. const Comp = {
  408. props: ['a', 'b'],
  409. setup(props: any) {
  410. watch(
  411. () => props.a + props.b,
  412. () => {
  413. calls.push('watcher 1')
  414. c.value++
  415. },
  416. { flush: 'pre' }
  417. )
  418. // #1777 chained pre-watcher
  419. watch(
  420. c,
  421. () => {
  422. calls.push('watcher 2')
  423. },
  424. { flush: 'pre' }
  425. )
  426. return () => {
  427. c.value
  428. calls.push('render')
  429. }
  430. }
  431. }
  432. const App = {
  433. render() {
  434. return h(Comp, { a: a.value, b: b.value })
  435. }
  436. }
  437. render(h(App), nodeOps.createElement('div'))
  438. expect(calls).toEqual(['render'])
  439. // both props are updated
  440. // should trigger pre-flush watcher first and only once
  441. // then trigger child render
  442. a.value++
  443. b.value++
  444. await nextTick()
  445. expect(calls).toEqual(['render', 'watcher 1', 'watcher 2', 'render'])
  446. })
  447. // #1852
  448. it('flush: post watcher should fire after template refs updated', async () => {
  449. const toggle = ref(false)
  450. let dom: TestElement | null = null
  451. const App = {
  452. setup() {
  453. const domRef = ref<TestElement | null>(null)
  454. watch(
  455. toggle,
  456. () => {
  457. dom = domRef.value
  458. },
  459. { flush: 'post' }
  460. )
  461. return () => {
  462. return toggle.value ? h('p', { ref: domRef }) : null
  463. }
  464. }
  465. }
  466. render(h(App), nodeOps.createElement('div'))
  467. expect(dom).toBe(null)
  468. toggle.value = true
  469. await nextTick()
  470. expect(dom!.tag).toBe('p')
  471. })
  472. it('deep', async () => {
  473. const state = reactive({
  474. nested: {
  475. count: ref(0)
  476. },
  477. array: [1, 2, 3],
  478. map: new Map([['a', 1], ['b', 2]]),
  479. set: new Set([1, 2, 3])
  480. })
  481. let dummy
  482. watch(
  483. () => state,
  484. state => {
  485. dummy = [
  486. state.nested.count,
  487. state.array[0],
  488. state.map.get('a'),
  489. state.set.has(1)
  490. ]
  491. },
  492. { deep: true }
  493. )
  494. state.nested.count++
  495. await nextTick()
  496. expect(dummy).toEqual([1, 1, 1, true])
  497. // nested array mutation
  498. state.array[0] = 2
  499. await nextTick()
  500. expect(dummy).toEqual([1, 2, 1, true])
  501. // nested map mutation
  502. state.map.set('a', 2)
  503. await nextTick()
  504. expect(dummy).toEqual([1, 2, 2, true])
  505. // nested set mutation
  506. state.set.delete(1)
  507. await nextTick()
  508. expect(dummy).toEqual([1, 2, 2, false])
  509. })
  510. it('watching deep ref', async () => {
  511. const count = ref(0)
  512. const double = computed(() => count.value * 2)
  513. const state = reactive([count, double])
  514. let dummy
  515. watch(
  516. () => state,
  517. state => {
  518. dummy = [state[0].value, state[1].value]
  519. },
  520. { deep: true }
  521. )
  522. count.value++
  523. await nextTick()
  524. expect(dummy).toEqual([1, 2])
  525. })
  526. it('immediate', async () => {
  527. const count = ref(0)
  528. const cb = jest.fn()
  529. watch(count, cb, { immediate: true })
  530. expect(cb).toHaveBeenCalledTimes(1)
  531. count.value++
  532. await nextTick()
  533. expect(cb).toHaveBeenCalledTimes(2)
  534. })
  535. it('immediate: triggers when initial value is null', async () => {
  536. const state = ref(null)
  537. const spy = jest.fn()
  538. watch(() => state.value, spy, { immediate: true })
  539. expect(spy).toHaveBeenCalled()
  540. })
  541. it('immediate: triggers when initial value is undefined', async () => {
  542. const state = ref()
  543. const spy = jest.fn()
  544. watch(() => state.value, spy, { immediate: true })
  545. expect(spy).toHaveBeenCalled()
  546. state.value = 3
  547. await nextTick()
  548. expect(spy).toHaveBeenCalledTimes(2)
  549. // testing if undefined can trigger the watcher
  550. state.value = undefined
  551. await nextTick()
  552. expect(spy).toHaveBeenCalledTimes(3)
  553. // it shouldn't trigger if the same value is set
  554. state.value = undefined
  555. await nextTick()
  556. expect(spy).toHaveBeenCalledTimes(3)
  557. })
  558. it('warn immediate option when using effect', async () => {
  559. const count = ref(0)
  560. let dummy
  561. watchEffect(
  562. () => {
  563. dummy = count.value
  564. },
  565. // @ts-ignore
  566. { immediate: false }
  567. )
  568. expect(dummy).toBe(0)
  569. expect(`"immediate" option is only respected`).toHaveBeenWarned()
  570. count.value++
  571. await nextTick()
  572. expect(dummy).toBe(1)
  573. })
  574. it('warn and not respect deep option when using effect', async () => {
  575. const arr = ref([1, [2]])
  576. const spy = jest.fn()
  577. watchEffect(
  578. () => {
  579. spy()
  580. return arr
  581. },
  582. // @ts-ignore
  583. { deep: true }
  584. )
  585. expect(spy).toHaveBeenCalledTimes(1)
  586. ;(arr.value[1] as Array<number>)[0] = 3
  587. await nextTick()
  588. expect(spy).toHaveBeenCalledTimes(1)
  589. expect(`"deep" option is only respected`).toHaveBeenWarned()
  590. })
  591. it('onTrack', async () => {
  592. const events: DebuggerEvent[] = []
  593. let dummy
  594. const onTrack = jest.fn((e: DebuggerEvent) => {
  595. events.push(e)
  596. })
  597. const obj = reactive({ foo: 1, bar: 2 })
  598. watchEffect(
  599. () => {
  600. dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
  601. },
  602. { onTrack }
  603. )
  604. await nextTick()
  605. expect(dummy).toEqual([1, true, ['foo', 'bar']])
  606. expect(onTrack).toHaveBeenCalledTimes(3)
  607. expect(events).toMatchObject([
  608. {
  609. target: obj,
  610. type: TrackOpTypes.GET,
  611. key: 'foo'
  612. },
  613. {
  614. target: obj,
  615. type: TrackOpTypes.HAS,
  616. key: 'bar'
  617. },
  618. {
  619. target: obj,
  620. type: TrackOpTypes.ITERATE,
  621. key: ITERATE_KEY
  622. }
  623. ])
  624. })
  625. it('onTrigger', async () => {
  626. const events: DebuggerEvent[] = []
  627. let dummy
  628. const onTrigger = jest.fn((e: DebuggerEvent) => {
  629. events.push(e)
  630. })
  631. const obj = reactive({ foo: 1 })
  632. watchEffect(
  633. () => {
  634. dummy = obj.foo
  635. },
  636. { onTrigger }
  637. )
  638. await nextTick()
  639. expect(dummy).toBe(1)
  640. obj.foo++
  641. await nextTick()
  642. expect(dummy).toBe(2)
  643. expect(onTrigger).toHaveBeenCalledTimes(1)
  644. expect(events[0]).toMatchObject({
  645. type: TriggerOpTypes.SET,
  646. key: 'foo',
  647. oldValue: 1,
  648. newValue: 2
  649. })
  650. // @ts-ignore
  651. delete obj.foo
  652. await nextTick()
  653. expect(dummy).toBeUndefined()
  654. expect(onTrigger).toHaveBeenCalledTimes(2)
  655. expect(events[1]).toMatchObject({
  656. type: TriggerOpTypes.DELETE,
  657. key: 'foo',
  658. oldValue: 2
  659. })
  660. })
  661. it('should work sync', () => {
  662. const v = ref(1)
  663. let calls = 0
  664. watch(
  665. v,
  666. () => {
  667. ++calls
  668. },
  669. {
  670. flush: 'sync'
  671. }
  672. )
  673. expect(calls).toBe(0)
  674. v.value++
  675. expect(calls).toBe(1)
  676. })
  677. test('should force trigger on triggerRef when watching a ref', async () => {
  678. const v = ref({ a: 1 })
  679. let sideEffect = 0
  680. watch(v, obj => {
  681. sideEffect = obj.a
  682. })
  683. v.value = v.value
  684. await nextTick()
  685. // should not trigger
  686. expect(sideEffect).toBe(0)
  687. v.value.a++
  688. await nextTick()
  689. // should not trigger
  690. expect(sideEffect).toBe(0)
  691. triggerRef(v)
  692. await nextTick()
  693. // should trigger now
  694. expect(sideEffect).toBe(2)
  695. })
  696. })