ref.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. import {
  2. type Ref,
  3. effect,
  4. isReactive,
  5. isRef,
  6. reactive,
  7. ref,
  8. toRef,
  9. toRefs,
  10. toValue,
  11. } from '../src/index'
  12. import { computed } from '@vue/runtime-dom'
  13. import { customRef, shallowRef, triggerRef, unref } from '../src/ref'
  14. import {
  15. isReadonly,
  16. isShallow,
  17. readonly,
  18. shallowReactive,
  19. } from '../src/reactive'
  20. describe('reactivity/ref', () => {
  21. it('should hold a value', () => {
  22. const a = ref(1)
  23. expect(a.value).toBe(1)
  24. a.value = 2
  25. expect(a.value).toBe(2)
  26. })
  27. it('should be reactive', () => {
  28. const a = ref(1)
  29. let dummy
  30. const fn = vi.fn(() => {
  31. dummy = a.value
  32. })
  33. effect(fn)
  34. expect(fn).toHaveBeenCalledTimes(1)
  35. expect(dummy).toBe(1)
  36. a.value = 2
  37. expect(fn).toHaveBeenCalledTimes(2)
  38. expect(dummy).toBe(2)
  39. // same value should not trigger
  40. a.value = 2
  41. expect(fn).toHaveBeenCalledTimes(2)
  42. })
  43. it('should make nested properties reactive', () => {
  44. const a = ref({
  45. count: 1,
  46. })
  47. let dummy
  48. effect(() => {
  49. dummy = a.value.count
  50. })
  51. expect(dummy).toBe(1)
  52. a.value.count = 2
  53. expect(dummy).toBe(2)
  54. })
  55. it('should work without initial value', () => {
  56. const a = ref()
  57. let dummy
  58. effect(() => {
  59. dummy = a.value
  60. })
  61. expect(dummy).toBe(undefined)
  62. a.value = 2
  63. expect(dummy).toBe(2)
  64. })
  65. it('should work like a normal property when nested in a reactive object', () => {
  66. const a = ref(1)
  67. const obj = reactive({
  68. a,
  69. b: {
  70. c: a,
  71. },
  72. })
  73. let dummy1: number
  74. let dummy2: number
  75. effect(() => {
  76. dummy1 = obj.a
  77. dummy2 = obj.b.c
  78. })
  79. const assertDummiesEqualTo = (val: number) =>
  80. [dummy1, dummy2].forEach(dummy => expect(dummy).toBe(val))
  81. assertDummiesEqualTo(1)
  82. a.value++
  83. assertDummiesEqualTo(2)
  84. obj.a++
  85. assertDummiesEqualTo(3)
  86. obj.b.c++
  87. assertDummiesEqualTo(4)
  88. })
  89. it('should unwrap nested ref in types', () => {
  90. const a = ref(0)
  91. const b = ref(a)
  92. expect(typeof (b.value + 1)).toBe('number')
  93. })
  94. it('should unwrap nested values in types', () => {
  95. const a = {
  96. b: ref(0),
  97. }
  98. const c = ref(a)
  99. expect(typeof (c.value.b + 1)).toBe('number')
  100. })
  101. it('should NOT unwrap ref types nested inside arrays', () => {
  102. const arr = ref([1, ref(3)]).value
  103. expect(isRef(arr[0])).toBe(false)
  104. expect(isRef(arr[1])).toBe(true)
  105. expect((arr[1] as Ref).value).toBe(3)
  106. })
  107. it('should unwrap ref types as props of arrays', () => {
  108. const arr = [ref(0)]
  109. const symbolKey = Symbol('')
  110. arr['' as any] = ref(1)
  111. arr[symbolKey as any] = ref(2)
  112. const arrRef = ref(arr).value
  113. expect(isRef(arrRef[0])).toBe(true)
  114. expect(isRef(arrRef['' as any])).toBe(false)
  115. expect(isRef(arrRef[symbolKey as any])).toBe(false)
  116. expect(arrRef['' as any]).toBe(1)
  117. expect(arrRef[symbolKey as any]).toBe(2)
  118. })
  119. it('should keep tuple types', () => {
  120. const tuple: [number, string, { a: number }, () => number, Ref<number>] = [
  121. 0,
  122. '1',
  123. { a: 1 },
  124. () => 0,
  125. ref(0),
  126. ]
  127. const tupleRef = ref(tuple)
  128. tupleRef.value[0]++
  129. expect(tupleRef.value[0]).toBe(1)
  130. tupleRef.value[1] += '1'
  131. expect(tupleRef.value[1]).toBe('11')
  132. tupleRef.value[2].a++
  133. expect(tupleRef.value[2].a).toBe(2)
  134. expect(tupleRef.value[3]()).toBe(0)
  135. tupleRef.value[4].value++
  136. expect(tupleRef.value[4].value).toBe(1)
  137. })
  138. it('should keep symbols', () => {
  139. const customSymbol = Symbol()
  140. const obj = {
  141. [Symbol.asyncIterator]: ref(1),
  142. [Symbol.hasInstance]: { a: ref('a') },
  143. [Symbol.isConcatSpreadable]: { b: ref(true) },
  144. [Symbol.iterator]: [ref(1)],
  145. [Symbol.match]: new Set<Ref<number>>(),
  146. [Symbol.matchAll]: new Map<number, Ref<string>>(),
  147. [Symbol.replace]: { arr: [ref('a')] },
  148. [Symbol.search]: { set: new Set<Ref<number>>() },
  149. [Symbol.species]: { map: new Map<number, Ref<string>>() },
  150. [Symbol.split]: new WeakSet<Ref<boolean>>(),
  151. [Symbol.toPrimitive]: new WeakMap<Ref<boolean>, string>(),
  152. [Symbol.toStringTag]: { weakSet: new WeakSet<Ref<boolean>>() },
  153. [Symbol.unscopables]: { weakMap: new WeakMap<Ref<boolean>, string>() },
  154. [customSymbol]: { arr: [ref(1)] },
  155. }
  156. const objRef = ref(obj)
  157. const keys: (keyof typeof obj)[] = [
  158. Symbol.asyncIterator,
  159. Symbol.hasInstance,
  160. Symbol.isConcatSpreadable,
  161. Symbol.iterator,
  162. Symbol.match,
  163. Symbol.matchAll,
  164. Symbol.replace,
  165. Symbol.search,
  166. Symbol.species,
  167. Symbol.split,
  168. Symbol.toPrimitive,
  169. Symbol.toStringTag,
  170. Symbol.unscopables,
  171. customSymbol,
  172. ]
  173. keys.forEach(key => {
  174. expect(objRef.value[key]).toStrictEqual(obj[key])
  175. })
  176. })
  177. test('unref', () => {
  178. expect(unref(1)).toBe(1)
  179. expect(unref(ref(1))).toBe(1)
  180. })
  181. test('shallowRef', () => {
  182. const sref = shallowRef({ a: 1 })
  183. expect(isReactive(sref.value)).toBe(false)
  184. let dummy
  185. effect(() => {
  186. dummy = sref.value.a
  187. })
  188. expect(dummy).toBe(1)
  189. sref.value = { a: 2 }
  190. expect(isReactive(sref.value)).toBe(false)
  191. expect(dummy).toBe(2)
  192. })
  193. test('shallowRef force trigger', () => {
  194. const sref = shallowRef({ a: 1 })
  195. let dummy
  196. effect(() => {
  197. dummy = sref.value.a
  198. })
  199. expect(dummy).toBe(1)
  200. sref.value.a = 2
  201. expect(dummy).toBe(1) // should not trigger yet
  202. // force trigger
  203. triggerRef(sref)
  204. expect(dummy).toBe(2)
  205. })
  206. test('shallowRef isShallow', () => {
  207. expect(isShallow(shallowRef({ a: 1 }))).toBe(true)
  208. })
  209. test('isRef', () => {
  210. expect(isRef(ref(1))).toBe(true)
  211. expect(isRef(computed(() => 1))).toBe(true)
  212. expect(isRef(0)).toBe(false)
  213. expect(isRef(1)).toBe(false)
  214. // an object that looks like a ref isn't necessarily a ref
  215. expect(isRef({ value: 0 })).toBe(false)
  216. })
  217. test('toRef', () => {
  218. const a = reactive({
  219. x: 1,
  220. })
  221. const x = toRef(a, 'x')
  222. const b = ref({ y: 1 })
  223. const c = toRef(b)
  224. const d = toRef({ z: 1 })
  225. expect(isRef(d)).toBe(true)
  226. expect(d.value.z).toBe(1)
  227. expect(c).toBe(b)
  228. expect(isRef(x)).toBe(true)
  229. expect(x.value).toBe(1)
  230. // source -> proxy
  231. a.x = 2
  232. expect(x.value).toBe(2)
  233. // proxy -> source
  234. x.value = 3
  235. expect(a.x).toBe(3)
  236. // reactivity
  237. let dummyX
  238. effect(() => {
  239. dummyX = x.value
  240. })
  241. expect(dummyX).toBe(x.value)
  242. // mutating source should trigger effect using the proxy refs
  243. a.x = 4
  244. expect(dummyX).toBe(4)
  245. // should keep ref
  246. const r = { x: ref(1) }
  247. expect(toRef(r, 'x')).toBe(r.x)
  248. })
  249. test('toRef on array', () => {
  250. const a = reactive(['a', 'b'])
  251. const r = toRef(a, 1)
  252. expect(r.value).toBe('b')
  253. r.value = 'c'
  254. expect(r.value).toBe('c')
  255. expect(a[1]).toBe('c')
  256. })
  257. test('toRef default value', () => {
  258. const a: { x: number | undefined } = { x: undefined }
  259. const x = toRef(a, 'x', 1)
  260. expect(x.value).toBe(1)
  261. a.x = 2
  262. expect(x.value).toBe(2)
  263. a.x = undefined
  264. expect(x.value).toBe(1)
  265. })
  266. test('toRef getter', () => {
  267. const x = toRef(() => 1)
  268. expect(x.value).toBe(1)
  269. expect(isRef(x)).toBe(true)
  270. expect(unref(x)).toBe(1)
  271. //@ts-expect-error
  272. expect(() => (x.value = 123)).toThrow()
  273. expect(isReadonly(x)).toBe(true)
  274. })
  275. test('toRefs', () => {
  276. const a = reactive({
  277. x: 1,
  278. y: 2,
  279. })
  280. const { x, y } = toRefs(a)
  281. expect(isRef(x)).toBe(true)
  282. expect(isRef(y)).toBe(true)
  283. expect(x.value).toBe(1)
  284. expect(y.value).toBe(2)
  285. // source -> proxy
  286. a.x = 2
  287. a.y = 3
  288. expect(x.value).toBe(2)
  289. expect(y.value).toBe(3)
  290. // proxy -> source
  291. x.value = 3
  292. y.value = 4
  293. expect(a.x).toBe(3)
  294. expect(a.y).toBe(4)
  295. // reactivity
  296. let dummyX, dummyY
  297. effect(() => {
  298. dummyX = x.value
  299. dummyY = y.value
  300. })
  301. expect(dummyX).toBe(x.value)
  302. expect(dummyY).toBe(y.value)
  303. // mutating source should trigger effect using the proxy refs
  304. a.x = 4
  305. a.y = 5
  306. expect(dummyX).toBe(4)
  307. expect(dummyY).toBe(5)
  308. })
  309. test('toRefs should warn on plain object', () => {
  310. toRefs({})
  311. expect(`toRefs() expects a reactive object`).toHaveBeenWarned()
  312. })
  313. test('toRefs should warn on plain array', () => {
  314. toRefs([])
  315. expect(`toRefs() expects a reactive object`).toHaveBeenWarned()
  316. })
  317. test('toRefs reactive array', () => {
  318. const arr = reactive(['a', 'b', 'c'])
  319. const refs = toRefs(arr)
  320. expect(Array.isArray(refs)).toBe(true)
  321. refs[0].value = '1'
  322. expect(arr[0]).toBe('1')
  323. arr[1] = '2'
  324. expect(refs[1].value).toBe('2')
  325. })
  326. test('customRef', () => {
  327. let value = 1
  328. let _trigger: () => void
  329. const custom = customRef((track, trigger) => ({
  330. get() {
  331. track()
  332. return value
  333. },
  334. set(newValue: number) {
  335. value = newValue
  336. _trigger = trigger
  337. },
  338. }))
  339. expect(isRef(custom)).toBe(true)
  340. let dummy
  341. effect(() => {
  342. dummy = custom.value
  343. })
  344. expect(dummy).toBe(1)
  345. custom.value = 2
  346. // should not trigger yet
  347. expect(dummy).toBe(1)
  348. _trigger!()
  349. expect(dummy).toBe(2)
  350. })
  351. test('should not trigger when setting value to same proxy', () => {
  352. const obj = reactive({ count: 0 })
  353. const a = ref(obj)
  354. const spy1 = vi.fn(() => a.value)
  355. effect(spy1)
  356. a.value = obj
  357. expect(spy1).toBeCalledTimes(1)
  358. const b = shallowRef(obj)
  359. const spy2 = vi.fn(() => b.value)
  360. effect(spy2)
  361. b.value = obj
  362. expect(spy2).toBeCalledTimes(1)
  363. })
  364. test('ref should preserve value shallow/readonly-ness', () => {
  365. const original = {}
  366. const r = reactive(original)
  367. const s = shallowReactive(original)
  368. const rr = readonly(original)
  369. const a = ref(original)
  370. expect(a.value).toBe(r)
  371. a.value = s
  372. expect(a.value).toBe(s)
  373. expect(a.value).not.toBe(r)
  374. a.value = rr
  375. expect(a.value).toBe(rr)
  376. expect(a.value).not.toBe(r)
  377. })
  378. test('should not trigger when setting the same raw object', () => {
  379. const obj = {}
  380. const r = ref(obj)
  381. const spy = vi.fn()
  382. effect(() => spy(r.value))
  383. expect(spy).toHaveBeenCalledTimes(1)
  384. r.value = obj
  385. expect(spy).toHaveBeenCalledTimes(1)
  386. })
  387. test('toValue', () => {
  388. const a = ref(1)
  389. const b = computed(() => a.value + 1)
  390. const c = () => a.value + 2
  391. const d = 4
  392. expect(toValue(a)).toBe(1)
  393. expect(toValue(b)).toBe(2)
  394. expect(toValue(c)).toBe(3)
  395. expect(toValue(d)).toBe(4)
  396. })
  397. test('ref w/ customRef w/ getterRef w/ objectRef should store value cache', () => {
  398. const refValue = ref(1)
  399. // @ts-expect-error private field
  400. expect(refValue._value).toBe(1)
  401. let customRefValueCache = 0
  402. const customRefValue = customRef((track, trigger) => {
  403. return {
  404. get() {
  405. track()
  406. return customRefValueCache
  407. },
  408. set(value: number) {
  409. customRefValueCache = value
  410. trigger()
  411. },
  412. }
  413. })
  414. customRefValue.value
  415. // @ts-expect-error internal field
  416. expect(customRefValue._value).toBe(0)
  417. const getterRefValue = toRef(() => 1)
  418. getterRefValue.value
  419. // @ts-expect-error internal field
  420. expect(getterRefValue._value).toBe(1)
  421. const objectRefValue = toRef({ value: 1 }, 'value')
  422. objectRefValue.value
  423. // @ts-expect-error internal field
  424. expect(objectRefValue._value).toBe(1)
  425. })
  426. })