apiWatch.spec.ts 9.7 KB

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