apiWatch.spec.ts 10 KB

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