apiWatch.spec.ts 12 KB

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