apiWatch.spec.ts 15 KB

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