apiWatch.spec.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import { watch, reactive, computed, nextTick, ref, h } from '../src/index'
  2. import { render, nodeOps, serializeInner } from '@vue/runtime-test'
  3. import {
  4. ITERATE_KEY,
  5. DebuggerEvent,
  6. TrackOpTypes,
  7. TriggerOpTypes
  8. } from '@vue/reactivity'
  9. // reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
  10. describe('api: watch', () => {
  11. it('basic usage', async () => {
  12. const state = reactive({ count: 0 })
  13. let dummy
  14. watch(() => {
  15. dummy = state.count
  16. })
  17. await nextTick()
  18. expect(dummy).toBe(0)
  19. state.count++
  20. await nextTick()
  21. expect(dummy).toBe(1)
  22. })
  23. it('watching single source: getter', async () => {
  24. const state = reactive({ count: 0 })
  25. let dummy
  26. watch(
  27. () => state.count,
  28. (count, prevCount) => {
  29. dummy = [count, prevCount]
  30. // assert types
  31. count + 1
  32. prevCount + 1
  33. }
  34. )
  35. await nextTick()
  36. expect(dummy).toMatchObject([0, undefined])
  37. state.count++
  38. await nextTick()
  39. expect(dummy).toMatchObject([1, 0])
  40. })
  41. it('watching single source: ref', async () => {
  42. const count = ref(0)
  43. let dummy
  44. watch(count, (count, prevCount) => {
  45. dummy = [count, prevCount]
  46. // assert types
  47. count + 1
  48. prevCount + 1
  49. })
  50. await nextTick()
  51. expect(dummy).toMatchObject([0, undefined])
  52. count.value++
  53. await nextTick()
  54. expect(dummy).toMatchObject([1, 0])
  55. })
  56. it('watching single source: computed ref', async () => {
  57. const count = ref(0)
  58. const plus = computed(() => count.value + 1)
  59. let dummy
  60. watch(plus, (count, prevCount) => {
  61. dummy = [count, prevCount]
  62. // assert types
  63. count + 1
  64. prevCount + 1
  65. })
  66. await nextTick()
  67. expect(dummy).toMatchObject([1, undefined])
  68. count.value++
  69. await nextTick()
  70. expect(dummy).toMatchObject([2, 1])
  71. })
  72. it('watching multiple sources', async () => {
  73. const state = reactive({ count: 1 })
  74. const count = ref(1)
  75. const plus = computed(() => count.value + 1)
  76. let dummy
  77. watch([() => state.count, count, plus], (vals, oldVals) => {
  78. dummy = [vals, oldVals]
  79. // assert types
  80. vals.concat(1)
  81. oldVals.concat(1)
  82. })
  83. await nextTick()
  84. expect(dummy).toMatchObject([[1, 1, 2], []])
  85. state.count++
  86. count.value++
  87. await nextTick()
  88. expect(dummy).toMatchObject([[2, 2, 3], [1, 1, 2]])
  89. })
  90. it('watching multiple sources: readonly array', async () => {
  91. const state = reactive({ count: 1 })
  92. const status = ref(false)
  93. let dummy
  94. watch([() => state.count, status] as const, (vals, oldVals) => {
  95. dummy = [vals, oldVals]
  96. let [count] = vals
  97. let [, oldStatus] = oldVals
  98. // assert types
  99. count + 1
  100. oldStatus === true
  101. })
  102. await nextTick()
  103. expect(dummy).toMatchObject([[1, false], []])
  104. state.count++
  105. status.value = false
  106. await nextTick()
  107. expect(dummy).toMatchObject([[2, false], [1, false]])
  108. })
  109. it('stopping the watcher', async () => {
  110. const state = reactive({ count: 0 })
  111. let dummy
  112. const stop = watch(() => {
  113. dummy = state.count
  114. })
  115. await nextTick()
  116. expect(dummy).toBe(0)
  117. stop()
  118. state.count++
  119. await nextTick()
  120. // should not update
  121. expect(dummy).toBe(0)
  122. })
  123. it('cleanup registration (basic)', async () => {
  124. const state = reactive({ count: 0 })
  125. const cleanup = jest.fn()
  126. let dummy
  127. const stop = watch(onCleanup => {
  128. onCleanup(cleanup)
  129. dummy = state.count
  130. })
  131. await nextTick()
  132. expect(dummy).toBe(0)
  133. state.count++
  134. await nextTick()
  135. expect(cleanup).toHaveBeenCalledTimes(1)
  136. expect(dummy).toBe(1)
  137. stop()
  138. expect(cleanup).toHaveBeenCalledTimes(2)
  139. })
  140. it('cleanup registration (with source)', async () => {
  141. const count = ref(0)
  142. const cleanup = jest.fn()
  143. let dummy
  144. const stop = watch(count, (count, prevCount, onCleanup) => {
  145. onCleanup(cleanup)
  146. dummy = count
  147. })
  148. await nextTick()
  149. expect(dummy).toBe(0)
  150. count.value++
  151. await nextTick()
  152. expect(cleanup).toHaveBeenCalledTimes(1)
  153. expect(dummy).toBe(1)
  154. stop()
  155. expect(cleanup).toHaveBeenCalledTimes(2)
  156. })
  157. it('flush timing: post', async () => {
  158. const count = ref(0)
  159. const assertion = jest.fn(count => {
  160. expect(serializeInner(root)).toBe(`${count}`)
  161. })
  162. const Comp = {
  163. setup() {
  164. watch(() => {
  165. assertion(count.value)
  166. })
  167. return () => count.value
  168. }
  169. }
  170. const root = nodeOps.createElement('div')
  171. render(h(Comp), root)
  172. await nextTick()
  173. expect(assertion).toHaveBeenCalledTimes(1)
  174. count.value++
  175. await nextTick()
  176. expect(assertion).toHaveBeenCalledTimes(2)
  177. })
  178. it('flush timing: pre', async () => {
  179. const count = ref(0)
  180. const count2 = ref(0)
  181. let callCount = 0
  182. const assertion = jest.fn((count, count2Value) => {
  183. callCount++
  184. // on mount, the watcher callback should be called before DOM render
  185. // on update, should be called before the count is updated
  186. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  187. expect(serializeInner(root)).toBe(expectedDOM)
  188. // in a pre-flush callback, all state should have been updated
  189. const expectedState = callCount === 1 ? 0 : 1
  190. expect(count2Value).toBe(expectedState)
  191. })
  192. const Comp = {
  193. setup() {
  194. watch(
  195. () => {
  196. assertion(count.value, count2.value)
  197. },
  198. {
  199. flush: 'pre'
  200. }
  201. )
  202. return () => count.value
  203. }
  204. }
  205. const root = nodeOps.createElement('div')
  206. render(h(Comp), root)
  207. await nextTick()
  208. expect(assertion).toHaveBeenCalledTimes(1)
  209. count.value++
  210. count2.value++
  211. await nextTick()
  212. // two mutations should result in 1 callback execution
  213. expect(assertion).toHaveBeenCalledTimes(2)
  214. })
  215. it('flush timing: sync', async () => {
  216. const count = ref(0)
  217. const count2 = ref(0)
  218. let callCount = 0
  219. const assertion = jest.fn(count => {
  220. callCount++
  221. // on mount, the watcher callback should be called before DOM render
  222. // on update, should be called before the count is updated
  223. const expectedDOM = callCount === 1 ? `` : `${count - 1}`
  224. expect(serializeInner(root)).toBe(expectedDOM)
  225. // in a sync callback, state mutation on the next line should not have
  226. // executed yet on the 2nd call, but will be on the 3rd call.
  227. const expectedState = callCount < 3 ? 0 : 1
  228. expect(count2.value).toBe(expectedState)
  229. })
  230. const Comp = {
  231. setup() {
  232. watch(
  233. () => {
  234. assertion(count.value)
  235. },
  236. {
  237. flush: 'sync'
  238. }
  239. )
  240. return () => count.value
  241. }
  242. }
  243. const root = nodeOps.createElement('div')
  244. render(h(Comp), root)
  245. await nextTick()
  246. expect(assertion).toHaveBeenCalledTimes(1)
  247. count.value++
  248. count2.value++
  249. await nextTick()
  250. expect(assertion).toHaveBeenCalledTimes(3)
  251. })
  252. it('deep', async () => {
  253. const state = reactive({
  254. nested: {
  255. count: ref(0)
  256. },
  257. array: [1, 2, 3],
  258. map: new Map([['a', 1], ['b', 2]]),
  259. set: new Set([1, 2, 3])
  260. })
  261. let dummy
  262. watch(
  263. () => state,
  264. state => {
  265. dummy = [
  266. state.nested.count,
  267. state.array[0],
  268. state.map.get('a'),
  269. state.set.has(1)
  270. ]
  271. },
  272. { deep: true }
  273. )
  274. await nextTick()
  275. expect(dummy).toEqual([0, 1, 1, true])
  276. state.nested.count++
  277. await nextTick()
  278. expect(dummy).toEqual([1, 1, 1, true])
  279. // nested array mutation
  280. state.array[0] = 2
  281. await nextTick()
  282. expect(dummy).toEqual([1, 2, 1, true])
  283. // nested map mutation
  284. state.map.set('a', 2)
  285. await nextTick()
  286. expect(dummy).toEqual([1, 2, 2, true])
  287. // nested set mutation
  288. state.set.delete(1)
  289. await nextTick()
  290. expect(dummy).toEqual([1, 2, 2, false])
  291. })
  292. it('lazy', async () => {
  293. const count = ref(0)
  294. const cb = jest.fn()
  295. watch(count, cb, { lazy: true })
  296. await nextTick()
  297. expect(cb).not.toHaveBeenCalled()
  298. count.value++
  299. await nextTick()
  300. expect(cb).toHaveBeenCalled()
  301. })
  302. it('onTrack', async () => {
  303. const events: DebuggerEvent[] = []
  304. let dummy
  305. const onTrack = jest.fn((e: DebuggerEvent) => {
  306. events.push(e)
  307. })
  308. const obj = reactive({ foo: 1, bar: 2 })
  309. watch(
  310. () => {
  311. dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
  312. },
  313. { onTrack }
  314. )
  315. await nextTick()
  316. expect(dummy).toEqual([1, true, ['foo', 'bar']])
  317. expect(onTrack).toHaveBeenCalledTimes(3)
  318. expect(events).toMatchObject([
  319. {
  320. target: obj,
  321. type: TrackOpTypes.GET,
  322. key: 'foo'
  323. },
  324. {
  325. target: obj,
  326. type: TrackOpTypes.HAS,
  327. key: 'bar'
  328. },
  329. {
  330. target: obj,
  331. type: TrackOpTypes.ITERATE,
  332. key: ITERATE_KEY
  333. }
  334. ])
  335. })
  336. it('onTrigger', async () => {
  337. const events: DebuggerEvent[] = []
  338. let dummy
  339. const onTrigger = jest.fn((e: DebuggerEvent) => {
  340. events.push(e)
  341. })
  342. const obj = reactive({ foo: 1 })
  343. watch(
  344. () => {
  345. dummy = obj.foo
  346. },
  347. { onTrigger }
  348. )
  349. await nextTick()
  350. expect(dummy).toBe(1)
  351. obj.foo++
  352. await nextTick()
  353. expect(dummy).toBe(2)
  354. expect(onTrigger).toHaveBeenCalledTimes(1)
  355. expect(events[0]).toMatchObject({
  356. type: TriggerOpTypes.SET,
  357. key: 'foo',
  358. oldValue: 1,
  359. newValue: 2
  360. })
  361. delete obj.foo
  362. await nextTick()
  363. expect(dummy).toBeUndefined()
  364. expect(onTrigger).toHaveBeenCalledTimes(2)
  365. expect(events[1]).toMatchObject({
  366. type: TriggerOpTypes.DELETE,
  367. key: 'foo',
  368. oldValue: 2
  369. })
  370. })
  371. })