|
| 1 | +import { describe, expect, it } from 'bun:test'; |
| 2 | +import { withStableRef } from './cache'; |
| 3 | + |
| 4 | +describe('withStableRef', () => { |
| 5 | + it('should return primitive values as is', () => { |
| 6 | + const toStableRef = withStableRef(); |
| 7 | + |
| 8 | + expect(toStableRef(42)).toBe(42); |
| 9 | + expect(toStableRef('hello')).toBe('hello'); |
| 10 | + expect(toStableRef(true)).toBe(true); |
| 11 | + expect(toStableRef(null)).toBe(null); |
| 12 | + expect(toStableRef(undefined)).toBe(undefined); |
| 13 | + }); |
| 14 | + |
| 15 | + it('should return the same reference for identical objects', () => { |
| 16 | + const toStableRef = withStableRef(); |
| 17 | + |
| 18 | + const obj1 = { a: 1, b: 2 }; |
| 19 | + const obj2 = { a: 1, b: 2 }; |
| 20 | + |
| 21 | + const ref1 = toStableRef(obj1); |
| 22 | + const ref2 = toStableRef(obj2); |
| 23 | + |
| 24 | + expect(ref1).toBe(ref2); |
| 25 | + expect(ref1).toBe(obj1); |
| 26 | + expect(ref1).not.toBe(obj2); |
| 27 | + }); |
| 28 | + |
| 29 | + it('should return the same reference for identical arrays', () => { |
| 30 | + const toStableRef = withStableRef(); |
| 31 | + |
| 32 | + const arr1 = [1, 2, 3]; |
| 33 | + const arr2 = [1, 2, 3]; |
| 34 | + |
| 35 | + const ref1 = toStableRef(arr1); |
| 36 | + const ref2 = toStableRef(arr2); |
| 37 | + |
| 38 | + expect(ref1).toBe(ref2); |
| 39 | + expect(ref1).toBe(arr1); |
| 40 | + expect(ref1).not.toBe(arr2); |
| 41 | + }); |
| 42 | + |
| 43 | + it('should return the same reference for identical nested objects', () => { |
| 44 | + const toStableRef = withStableRef(); |
| 45 | + |
| 46 | + const obj1 = { a: { b: 1 }, c: [2, 3] }; |
| 47 | + const obj2 = { a: { b: 1 }, c: [2, 3] }; |
| 48 | + |
| 49 | + const ref1 = toStableRef(obj1); |
| 50 | + const ref2 = toStableRef(obj2); |
| 51 | + |
| 52 | + expect(ref1).toBe(ref2); |
| 53 | + expect(ref1).toBe(obj1); |
| 54 | + expect(ref1).not.toBe(obj2); |
| 55 | + }); |
| 56 | + |
| 57 | + it('should return different references for different objects', () => { |
| 58 | + const toStableRef = withStableRef(); |
| 59 | + |
| 60 | + const obj1 = { a: 1 }; |
| 61 | + const obj2 = { a: 2 }; |
| 62 | + |
| 63 | + const ref1 = toStableRef(obj1); |
| 64 | + const ref2 = toStableRef(obj2); |
| 65 | + |
| 66 | + expect(ref1).not.toBe(ref2); |
| 67 | + }); |
| 68 | + |
| 69 | + it('should maintain reference stability across multiple calls', () => { |
| 70 | + const toStableRef = withStableRef(); |
| 71 | + |
| 72 | + const obj = { a: 1 }; |
| 73 | + const ref1 = toStableRef(obj); |
| 74 | + const ref2 = toStableRef(obj); |
| 75 | + const ref3 = toStableRef(obj); |
| 76 | + |
| 77 | + expect(ref1).toBe(ref2); |
| 78 | + expect(ref2).toBe(ref3); |
| 79 | + }); |
| 80 | +}); |
0 commit comments