lazy.test.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { describe, expect, test } from "bun:test"
  2. import { lazy } from "../../src/util/lazy"
  3. describe("util.lazy", () => {
  4. test("should call function only once", () => {
  5. let callCount = 0
  6. const getValue = () => {
  7. callCount++
  8. return "expensive value"
  9. }
  10. const lazyValue = lazy(getValue)
  11. expect(callCount).toBe(0)
  12. const result1 = lazyValue()
  13. expect(result1).toBe("expensive value")
  14. expect(callCount).toBe(1)
  15. const result2 = lazyValue()
  16. expect(result2).toBe("expensive value")
  17. expect(callCount).toBe(1)
  18. })
  19. test("should preserve the same reference", () => {
  20. const obj = { value: 42 }
  21. const lazyObj = lazy(() => obj)
  22. const result1 = lazyObj()
  23. const result2 = lazyObj()
  24. expect(result1).toBe(obj)
  25. expect(result2).toBe(obj)
  26. expect(result1).toBe(result2)
  27. })
  28. test("should work with different return types", () => {
  29. const lazyString = lazy(() => "string")
  30. const lazyNumber = lazy(() => 123)
  31. const lazyBoolean = lazy(() => true)
  32. const lazyNull = lazy(() => null)
  33. const lazyUndefined = lazy(() => undefined)
  34. expect(lazyString()).toBe("string")
  35. expect(lazyNumber()).toBe(123)
  36. expect(lazyBoolean()).toBe(true)
  37. expect(lazyNull()).toBe(null)
  38. expect(lazyUndefined()).toBe(undefined)
  39. })
  40. })