apiWatch.spec.ts 12 KB

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