apiWatch.spec.ts 10 KB

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