apiWatch.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 multiple sources', async () => {
  82. const state = reactive({ count: 1 })
  83. const count = ref(1)
  84. const plus = computed(() => count.value + 1)
  85. let dummy
  86. watch([() => state.count, count, plus], (vals, oldVals) => {
  87. dummy = [vals, oldVals]
  88. // assert types
  89. vals.concat(1)
  90. oldVals.concat(1)
  91. })
  92. state.count++
  93. count.value++
  94. await nextTick()
  95. expect(dummy).toMatchObject([[2, 2, 3], [1, 1, 2]])
  96. })
  97. it('watching multiple sources: readonly array', async () => {
  98. const state = reactive({ count: 1 })
  99. const status = ref(false)
  100. let dummy
  101. watch([() => state.count, status] as const, (vals, oldVals) => {
  102. dummy = [vals, oldVals]
  103. const [count] = vals
  104. const [, oldStatus] = oldVals
  105. // assert types
  106. count + 1
  107. oldStatus === true
  108. })
  109. state.count++
  110. status.value = true
  111. await nextTick()
  112. expect(dummy).toMatchObject([[2, true], [1, false]])
  113. })
  114. it('stopping the watcher (effect)', async () => {
  115. const state = reactive({ count: 0 })
  116. let dummy
  117. const stop = watchEffect(() => {
  118. dummy = state.count
  119. })
  120. expect(dummy).toBe(0)
  121. stop()
  122. state.count++
  123. await nextTick()
  124. // should not update
  125. expect(dummy).toBe(0)
  126. })
  127. it('stopping the watcher (with source)', async () => {
  128. const state = reactive({ count: 0 })
  129. let dummy
  130. const stop = watch(
  131. () => state.count,
  132. count => {
  133. dummy = count
  134. }
  135. )
  136. state.count++
  137. await nextTick()
  138. expect(dummy).toBe(1)
  139. stop()
  140. state.count++
  141. await nextTick()
  142. // should not update
  143. expect(dummy).toBe(1)
  144. })
  145. it('cleanup registration (effect)', async () => {
  146. const state = reactive({ count: 0 })
  147. const cleanup = jest.fn()
  148. let dummy
  149. const stop = watchEffect(onCleanup => {
  150. onCleanup(cleanup)
  151. dummy = state.count
  152. })
  153. expect(dummy).toBe(0)
  154. state.count++
  155. await nextTick()
  156. expect(cleanup).toHaveBeenCalledTimes(1)
  157. expect(dummy).toBe(1)
  158. stop()
  159. expect(cleanup).toHaveBeenCalledTimes(2)
  160. })
  161. it('cleanup registration (with source)', async () => {
  162. const count = ref(0)
  163. const cleanup = jest.fn()
  164. let dummy
  165. const stop = watch(count, (count, prevCount, onCleanup) => {
  166. onCleanup(cleanup)
  167. dummy = count
  168. })
  169. count.value++
  170. await nextTick()
  171. expect(cleanup).toHaveBeenCalledTimes(0)
  172. expect(dummy).toBe(1)
  173. count.value++
  174. await nextTick()
  175. expect(cleanup).toHaveBeenCalledTimes(1)
  176. expect(dummy).toBe(2)
  177. stop()
  178. expect(cleanup).toHaveBeenCalledTimes(2)
  179. })
  180. it('flush timing: post (default)', async () => {
  181. const count = ref(0)
  182. let callCount = 0
  183. const assertion = jest.fn(count => {
  184. callCount++
  185. // on mount, the watcher callback should be called before DOM render
  186. // on update, should be called after the count is updated
  187. const expectedDOM = callCount === 1 ? `` : `${count}`
  188. expect(serializeInner(root)).toBe(expectedDOM)
  189. })
  190. const Comp = {
  191. setup() {
  192. watchEffect(() => {
  193. assertion(count.value)
  194. })
  195. return () => count.value
  196. }
  197. }
  198. const root = nodeOps.createElement('div')
  199. render(h(Comp), root)
  200. expect(assertion).toHaveBeenCalledTimes(1)
  201. count.value++
  202. await nextTick()
  203. expect(assertion).toHaveBeenCalledTimes(2)
  204. })
  205. it('flush timing: pre', async () => {
  206. const count = ref(0)
  207. const count2 = ref(0)
  208. let callCount = 0
  209. const assertion = jest.fn((count, count2Value) => {
  210. callCount++
  211. // on mount, the watcher callback should be called before DOM render
  212. // on update, should be called before the count is updated
  213. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  214. expect(serializeInner(root)).toBe(expectedDOM)
  215. // in a pre-flush callback, all state should have been updated
  216. const expectedState = callCount === 1 ? 0 : 1
  217. expect(count2Value).toBe(expectedState)
  218. })
  219. const Comp = {
  220. setup() {
  221. watchEffect(
  222. () => {
  223. assertion(count.value, count2.value)
  224. },
  225. {
  226. flush: 'pre'
  227. }
  228. )
  229. return () => count.value
  230. }
  231. }
  232. const root = nodeOps.createElement('div')
  233. render(h(Comp), root)
  234. expect(assertion).toHaveBeenCalledTimes(1)
  235. count.value++
  236. count2.value++
  237. await nextTick()
  238. // two mutations should result in 1 callback execution
  239. expect(assertion).toHaveBeenCalledTimes(2)
  240. })
  241. it('flush timing: sync', async () => {
  242. const count = ref(0)
  243. const count2 = ref(0)
  244. let callCount = 0
  245. const assertion = jest.fn(count => {
  246. callCount++
  247. // on mount, the watcher callback should be called before DOM render
  248. // on update, should be called before the count is updated
  249. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  250. expect(serializeInner(root)).toBe(expectedDOM)
  251. // in a sync callback, state mutation on the next line should not have
  252. // executed yet on the 2nd call, but will be on the 3rd call.
  253. const expectedState = callCount < 3 ? 0 : 1
  254. expect(count2.value).toBe(expectedState)
  255. })
  256. const Comp = {
  257. setup() {
  258. watchEffect(
  259. () => {
  260. assertion(count.value)
  261. },
  262. {
  263. flush: 'sync'
  264. }
  265. )
  266. return () => count.value
  267. }
  268. }
  269. const root = nodeOps.createElement('div')
  270. render(h(Comp), root)
  271. expect(assertion).toHaveBeenCalledTimes(1)
  272. count.value++
  273. count2.value++
  274. await nextTick()
  275. expect(assertion).toHaveBeenCalledTimes(3)
  276. })
  277. it('deep', async () => {
  278. const state = reactive({
  279. nested: {
  280. count: ref(0)
  281. },
  282. array: [1, 2, 3],
  283. map: new Map([['a', 1], ['b', 2]]),
  284. set: new Set([1, 2, 3])
  285. })
  286. let dummy
  287. watch(
  288. () => state,
  289. state => {
  290. dummy = [
  291. state.nested.count,
  292. state.array[0],
  293. state.map.get('a'),
  294. state.set.has(1)
  295. ]
  296. },
  297. { deep: true }
  298. )
  299. state.nested.count++
  300. await nextTick()
  301. expect(dummy).toEqual([1, 1, 1, true])
  302. // nested array mutation
  303. state.array[0] = 2
  304. await nextTick()
  305. expect(dummy).toEqual([1, 2, 1, true])
  306. // nested map mutation
  307. state.map.set('a', 2)
  308. await nextTick()
  309. expect(dummy).toEqual([1, 2, 2, true])
  310. // nested set mutation
  311. state.set.delete(1)
  312. await nextTick()
  313. expect(dummy).toEqual([1, 2, 2, false])
  314. })
  315. it('immediate', async () => {
  316. const count = ref(0)
  317. const cb = jest.fn()
  318. watch(count, cb, { immediate: true })
  319. expect(cb).toHaveBeenCalledTimes(1)
  320. count.value++
  321. await nextTick()
  322. expect(cb).toHaveBeenCalledTimes(2)
  323. })
  324. it('immediate: triggers when initial value is null', async () => {
  325. const state = ref(null)
  326. const spy = jest.fn()
  327. watch(() => state.value, spy, { immediate: true })
  328. expect(spy).toHaveBeenCalled()
  329. })
  330. it('immediate: triggers when initial value is undefined', async () => {
  331. const state = ref()
  332. const spy = jest.fn()
  333. watch(() => state.value, spy, { immediate: true })
  334. expect(spy).toHaveBeenCalled()
  335. state.value = 3
  336. await nextTick()
  337. expect(spy).toHaveBeenCalledTimes(2)
  338. // testing if undefined can trigger the watcher
  339. state.value = undefined
  340. await nextTick()
  341. expect(spy).toHaveBeenCalledTimes(3)
  342. // it shouldn't trigger if the same value is set
  343. state.value = undefined
  344. await nextTick()
  345. expect(spy).toHaveBeenCalledTimes(3)
  346. })
  347. it('warn immediate option when using effect', async () => {
  348. const count = ref(0)
  349. let dummy
  350. watchEffect(
  351. () => {
  352. dummy = count.value
  353. },
  354. // @ts-ignore
  355. { immediate: false }
  356. )
  357. expect(dummy).toBe(0)
  358. expect(`"immediate" option is only respected`).toHaveBeenWarned()
  359. count.value++
  360. await nextTick()
  361. expect(dummy).toBe(1)
  362. })
  363. it('warn and not respect deep option when using effect', async () => {
  364. const arr = ref([1, [2]])
  365. const spy = jest.fn()
  366. watchEffect(
  367. () => {
  368. spy()
  369. return arr
  370. },
  371. // @ts-ignore
  372. { deep: true }
  373. )
  374. expect(spy).toHaveBeenCalledTimes(1)
  375. ;(arr.value[1] as Array<number>)[0] = 3
  376. await nextTick()
  377. expect(spy).toHaveBeenCalledTimes(1)
  378. expect(`"deep" option is only respected`).toHaveBeenWarned()
  379. })
  380. it('onTrack', async () => {
  381. const events: DebuggerEvent[] = []
  382. let dummy
  383. const onTrack = jest.fn((e: DebuggerEvent) => {
  384. events.push(e)
  385. })
  386. const obj = reactive({ foo: 1, bar: 2 })
  387. watchEffect(
  388. () => {
  389. dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
  390. },
  391. { onTrack }
  392. )
  393. await nextTick()
  394. expect(dummy).toEqual([1, true, ['foo', 'bar']])
  395. expect(onTrack).toHaveBeenCalledTimes(3)
  396. expect(events).toMatchObject([
  397. {
  398. target: obj,
  399. type: TrackOpTypes.GET,
  400. key: 'foo'
  401. },
  402. {
  403. target: obj,
  404. type: TrackOpTypes.HAS,
  405. key: 'bar'
  406. },
  407. {
  408. target: obj,
  409. type: TrackOpTypes.ITERATE,
  410. key: ITERATE_KEY
  411. }
  412. ])
  413. })
  414. it('onTrigger', async () => {
  415. const events: DebuggerEvent[] = []
  416. let dummy
  417. const onTrigger = jest.fn((e: DebuggerEvent) => {
  418. events.push(e)
  419. })
  420. const obj = reactive({ foo: 1 })
  421. watchEffect(
  422. () => {
  423. dummy = obj.foo
  424. },
  425. { onTrigger }
  426. )
  427. await nextTick()
  428. expect(dummy).toBe(1)
  429. obj.foo++
  430. await nextTick()
  431. expect(dummy).toBe(2)
  432. expect(onTrigger).toHaveBeenCalledTimes(1)
  433. expect(events[0]).toMatchObject({
  434. type: TriggerOpTypes.SET,
  435. key: 'foo',
  436. oldValue: 1,
  437. newValue: 2
  438. })
  439. delete obj.foo
  440. await nextTick()
  441. expect(dummy).toBeUndefined()
  442. expect(onTrigger).toHaveBeenCalledTimes(2)
  443. expect(events[1]).toMatchObject({
  444. type: TriggerOpTypes.DELETE,
  445. key: 'foo',
  446. oldValue: 2
  447. })
  448. })
  449. })