apiWatch.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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: pre (default)', async () => {
  250. const count = ref(0)
  251. const count2 = ref(0)
  252. let callCount = 0
  253. let result1
  254. let result2
  255. const assertion = jest.fn((count, count2Value) => {
  256. callCount++
  257. // on mount, the watcher callback should be called before DOM render
  258. // on update, should be called before the count is updated
  259. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  260. result1 = serializeInner(root) === expectedDOM
  261. // in a pre-flush callback, all state should have been updated
  262. const expectedState = callCount - 1
  263. result2 = count === expectedState && count2Value === expectedState
  264. })
  265. const Comp = {
  266. setup() {
  267. watchEffect(() => {
  268. assertion(count.value, count2.value)
  269. })
  270. return () => count.value
  271. }
  272. }
  273. const root = nodeOps.createElement('div')
  274. render(h(Comp), root)
  275. expect(assertion).toHaveBeenCalledTimes(1)
  276. expect(result1).toBe(true)
  277. expect(result2).toBe(true)
  278. count.value++
  279. count2.value++
  280. await nextTick()
  281. // two mutations should result in 1 callback execution
  282. expect(assertion).toHaveBeenCalledTimes(2)
  283. expect(result1).toBe(true)
  284. expect(result2).toBe(true)
  285. })
  286. it('flush timing: post', async () => {
  287. const count = ref(0)
  288. let result
  289. const assertion = jest.fn(count => {
  290. result = serializeInner(root) === `${count}`
  291. })
  292. const Comp = {
  293. setup() {
  294. watchEffect(
  295. () => {
  296. assertion(count.value)
  297. },
  298. { flush: 'post' }
  299. )
  300. return () => count.value
  301. }
  302. }
  303. const root = nodeOps.createElement('div')
  304. render(h(Comp), root)
  305. expect(assertion).toHaveBeenCalledTimes(1)
  306. expect(result).toBe(true)
  307. count.value++
  308. await nextTick()
  309. expect(assertion).toHaveBeenCalledTimes(2)
  310. expect(result).toBe(true)
  311. })
  312. it('flush timing: sync', async () => {
  313. const count = ref(0)
  314. const count2 = ref(0)
  315. let callCount = 0
  316. let result1
  317. let result2
  318. const assertion = jest.fn(count => {
  319. callCount++
  320. // on mount, the watcher callback should be called before DOM render
  321. // on update, should be called before the count is updated
  322. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  323. result1 = serializeInner(root) === expectedDOM
  324. // in a sync callback, state mutation on the next line should not have
  325. // executed yet on the 2nd call, but will be on the 3rd call.
  326. const expectedState = callCount < 3 ? 0 : 1
  327. result2 = count2.value === expectedState
  328. })
  329. const Comp = {
  330. setup() {
  331. watchEffect(
  332. () => {
  333. assertion(count.value)
  334. },
  335. {
  336. flush: 'sync'
  337. }
  338. )
  339. return () => count.value
  340. }
  341. }
  342. const root = nodeOps.createElement('div')
  343. render(h(Comp), root)
  344. expect(assertion).toHaveBeenCalledTimes(1)
  345. expect(result1).toBe(true)
  346. expect(result2).toBe(true)
  347. count.value++
  348. count2.value++
  349. await nextTick()
  350. expect(assertion).toHaveBeenCalledTimes(3)
  351. expect(result1).toBe(true)
  352. expect(result2).toBe(true)
  353. })
  354. it('should not fire on component unmount w/ flush: post', async () => {
  355. const toggle = ref(true)
  356. const cb = jest.fn()
  357. const Comp = {
  358. setup() {
  359. watch(toggle, cb, { flush: 'post' })
  360. },
  361. render() {}
  362. }
  363. const App = {
  364. render() {
  365. return toggle.value ? h(Comp) : null
  366. }
  367. }
  368. render(h(App), nodeOps.createElement('div'))
  369. expect(cb).not.toHaveBeenCalled()
  370. toggle.value = false
  371. await nextTick()
  372. expect(cb).not.toHaveBeenCalled()
  373. })
  374. it('should fire on component unmount w/ flush: pre', async () => {
  375. const toggle = ref(true)
  376. const cb = jest.fn()
  377. const Comp = {
  378. setup() {
  379. watch(toggle, cb, { flush: 'pre' })
  380. },
  381. render() {}
  382. }
  383. const App = {
  384. render() {
  385. return toggle.value ? h(Comp) : null
  386. }
  387. }
  388. render(h(App), nodeOps.createElement('div'))
  389. expect(cb).not.toHaveBeenCalled()
  390. toggle.value = false
  391. await nextTick()
  392. expect(cb).toHaveBeenCalledTimes(1)
  393. })
  394. // #1763
  395. it('flush: pre watcher watching props should fire before child update', async () => {
  396. const a = ref(0)
  397. const b = ref(0)
  398. const c = ref(0)
  399. const calls: string[] = []
  400. const Comp = {
  401. props: ['a', 'b'],
  402. setup(props: any) {
  403. watch(
  404. () => props.a + props.b,
  405. () => {
  406. calls.push('watcher 1')
  407. c.value++
  408. },
  409. { flush: 'pre' }
  410. )
  411. // #1777 chained pre-watcher
  412. watch(
  413. c,
  414. () => {
  415. calls.push('watcher 2')
  416. },
  417. { flush: 'pre' }
  418. )
  419. return () => {
  420. c.value
  421. calls.push('render')
  422. }
  423. }
  424. }
  425. const App = {
  426. render() {
  427. return h(Comp, { a: a.value, b: b.value })
  428. }
  429. }
  430. render(h(App), nodeOps.createElement('div'))
  431. expect(calls).toEqual(['render'])
  432. // both props are updated
  433. // should trigger pre-flush watcher first and only once
  434. // then trigger child render
  435. a.value++
  436. b.value++
  437. await nextTick()
  438. expect(calls).toEqual(['render', 'watcher 1', 'watcher 2', 'render'])
  439. })
  440. // #1852
  441. it('flush: post watcher should fire after template refs updated', async () => {
  442. const toggle = ref(false)
  443. let dom: TestElement | null = null
  444. const App = {
  445. setup() {
  446. const domRef = ref<TestElement | null>(null)
  447. watch(
  448. toggle,
  449. () => {
  450. dom = domRef.value
  451. },
  452. { flush: 'post' }
  453. )
  454. return () => {
  455. return toggle.value ? h('p', { ref: domRef }) : null
  456. }
  457. }
  458. }
  459. render(h(App), nodeOps.createElement('div'))
  460. expect(dom).toBe(null)
  461. toggle.value = true
  462. await nextTick()
  463. expect(dom!.tag).toBe('p')
  464. })
  465. it('deep', async () => {
  466. const state = reactive({
  467. nested: {
  468. count: ref(0)
  469. },
  470. array: [1, 2, 3],
  471. map: new Map([['a', 1], ['b', 2]]),
  472. set: new Set([1, 2, 3])
  473. })
  474. let dummy
  475. watch(
  476. () => state,
  477. state => {
  478. dummy = [
  479. state.nested.count,
  480. state.array[0],
  481. state.map.get('a'),
  482. state.set.has(1)
  483. ]
  484. },
  485. { deep: true }
  486. )
  487. state.nested.count++
  488. await nextTick()
  489. expect(dummy).toEqual([1, 1, 1, true])
  490. // nested array mutation
  491. state.array[0] = 2
  492. await nextTick()
  493. expect(dummy).toEqual([1, 2, 1, true])
  494. // nested map mutation
  495. state.map.set('a', 2)
  496. await nextTick()
  497. expect(dummy).toEqual([1, 2, 2, true])
  498. // nested set mutation
  499. state.set.delete(1)
  500. await nextTick()
  501. expect(dummy).toEqual([1, 2, 2, false])
  502. })
  503. it('watching deep ref', async () => {
  504. const count = ref(0)
  505. const double = computed(() => count.value * 2)
  506. const state = reactive([count, double])
  507. let dummy
  508. watch(
  509. () => state,
  510. state => {
  511. dummy = [state[0].value, state[1].value]
  512. },
  513. { deep: true }
  514. )
  515. count.value++
  516. await nextTick()
  517. expect(dummy).toEqual([1, 2])
  518. })
  519. it('immediate', async () => {
  520. const count = ref(0)
  521. const cb = jest.fn()
  522. watch(count, cb, { immediate: true })
  523. expect(cb).toHaveBeenCalledTimes(1)
  524. count.value++
  525. await nextTick()
  526. expect(cb).toHaveBeenCalledTimes(2)
  527. })
  528. it('immediate: triggers when initial value is null', async () => {
  529. const state = ref(null)
  530. const spy = jest.fn()
  531. watch(() => state.value, spy, { immediate: true })
  532. expect(spy).toHaveBeenCalled()
  533. })
  534. it('immediate: triggers when initial value is undefined', async () => {
  535. const state = ref()
  536. const spy = jest.fn()
  537. watch(() => state.value, spy, { immediate: true })
  538. expect(spy).toHaveBeenCalled()
  539. state.value = 3
  540. await nextTick()
  541. expect(spy).toHaveBeenCalledTimes(2)
  542. // testing if undefined can trigger the watcher
  543. state.value = undefined
  544. await nextTick()
  545. expect(spy).toHaveBeenCalledTimes(3)
  546. // it shouldn't trigger if the same value is set
  547. state.value = undefined
  548. await nextTick()
  549. expect(spy).toHaveBeenCalledTimes(3)
  550. })
  551. it('warn immediate option when using effect', async () => {
  552. const count = ref(0)
  553. let dummy
  554. watchEffect(
  555. () => {
  556. dummy = count.value
  557. },
  558. // @ts-ignore
  559. { immediate: false }
  560. )
  561. expect(dummy).toBe(0)
  562. expect(`"immediate" option is only respected`).toHaveBeenWarned()
  563. count.value++
  564. await nextTick()
  565. expect(dummy).toBe(1)
  566. })
  567. it('warn and not respect deep option when using effect', async () => {
  568. const arr = ref([1, [2]])
  569. const spy = jest.fn()
  570. watchEffect(
  571. () => {
  572. spy()
  573. return arr
  574. },
  575. // @ts-ignore
  576. { deep: true }
  577. )
  578. expect(spy).toHaveBeenCalledTimes(1)
  579. ;(arr.value[1] as Array<number>)[0] = 3
  580. await nextTick()
  581. expect(spy).toHaveBeenCalledTimes(1)
  582. expect(`"deep" option is only respected`).toHaveBeenWarned()
  583. })
  584. it('onTrack', async () => {
  585. const events: DebuggerEvent[] = []
  586. let dummy
  587. const onTrack = jest.fn((e: DebuggerEvent) => {
  588. events.push(e)
  589. })
  590. const obj = reactive({ foo: 1, bar: 2 })
  591. watchEffect(
  592. () => {
  593. dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
  594. },
  595. { onTrack }
  596. )
  597. await nextTick()
  598. expect(dummy).toEqual([1, true, ['foo', 'bar']])
  599. expect(onTrack).toHaveBeenCalledTimes(3)
  600. expect(events).toMatchObject([
  601. {
  602. target: obj,
  603. type: TrackOpTypes.GET,
  604. key: 'foo'
  605. },
  606. {
  607. target: obj,
  608. type: TrackOpTypes.HAS,
  609. key: 'bar'
  610. },
  611. {
  612. target: obj,
  613. type: TrackOpTypes.ITERATE,
  614. key: ITERATE_KEY
  615. }
  616. ])
  617. })
  618. it('onTrigger', async () => {
  619. const events: DebuggerEvent[] = []
  620. let dummy
  621. const onTrigger = jest.fn((e: DebuggerEvent) => {
  622. events.push(e)
  623. })
  624. const obj = reactive({ foo: 1 })
  625. watchEffect(
  626. () => {
  627. dummy = obj.foo
  628. },
  629. { onTrigger }
  630. )
  631. await nextTick()
  632. expect(dummy).toBe(1)
  633. obj.foo++
  634. await nextTick()
  635. expect(dummy).toBe(2)
  636. expect(onTrigger).toHaveBeenCalledTimes(1)
  637. expect(events[0]).toMatchObject({
  638. type: TriggerOpTypes.SET,
  639. key: 'foo',
  640. oldValue: 1,
  641. newValue: 2
  642. })
  643. // @ts-ignore
  644. delete obj.foo
  645. await nextTick()
  646. expect(dummy).toBeUndefined()
  647. expect(onTrigger).toHaveBeenCalledTimes(2)
  648. expect(events[1]).toMatchObject({
  649. type: TriggerOpTypes.DELETE,
  650. key: 'foo',
  651. oldValue: 2
  652. })
  653. })
  654. it('should work sync', () => {
  655. const v = ref(1)
  656. let calls = 0
  657. watch(
  658. v,
  659. () => {
  660. ++calls
  661. },
  662. {
  663. flush: 'sync'
  664. }
  665. )
  666. expect(calls).toBe(0)
  667. v.value++
  668. expect(calls).toBe(1)
  669. })
  670. test('should force trigger on triggerRef when watching a ref', async () => {
  671. const v = ref({ a: 1 })
  672. let sideEffect = 0
  673. watch(v, obj => {
  674. sideEffect = obj.a
  675. })
  676. v.value = v.value
  677. await nextTick()
  678. // should not trigger
  679. expect(sideEffect).toBe(0)
  680. v.value.a++
  681. await nextTick()
  682. // should not trigger
  683. expect(sideEffect).toBe(0)
  684. triggerRef(v)
  685. await nextTick()
  686. // should trigger now
  687. expect(sideEffect).toBe(2)
  688. })
  689. // #2125
  690. test('watchEffect should not recursively trigger itself', async () => {
  691. const spy = jest.fn()
  692. const price = ref(10)
  693. const history = ref<number[]>([])
  694. watchEffect(() => {
  695. history.value.push(price.value)
  696. spy()
  697. })
  698. await nextTick()
  699. expect(spy).toHaveBeenCalledTimes(1)
  700. })
  701. })