apiWatch.spec.ts 14 KB

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