apiWatch.spec.ts 13 KB

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