Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

kv.worker.test.ts

57 lines1.8 KB

1import { describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3​
4import {
5 contentHash,
6 getByHash,
7 getJson,
8 putByHash,
9 putJson,
10 schemaKey,
11 stableStringify,
12} from './kv.ts'
13​
14describe('stableStringify', () => {
15 it('is independent of object key order, including nested objects', () => {
16 expect(stableStringify({ b: 1, a: { d: 2, c: [{ f: 3, e: 4 }] } })).toBe(
17 stableStringify({ a: { c: [{ e: 4, f: 3 }], d: 2 }, b: 1 }),
18 )
19 })
20​
21 it('preserves array order', () => {
22 expect(stableStringify([2, 1])).toBe('[2,1]')
23 })
24})
25​
26describe('contentHash', () => {
27 it('produces a stable sha-256 hex digest for equivalent values', async () => {
28 const a = await contentHash({ x: 1, y: 2 })
29 const b = await contentHash({ y: 2, x: 1 })
30 expect(a).toBe(b)
31 expect(a).toMatch(/^[0-9a-f]{64}$/)
32 })
33​
34 it('differs for different values', async () => {
35 expect(await contentHash({ x: 1 })).not.toBe(await contentHash({ x: 2 }))
36 })
37})
38​
39describe('kv json helpers (real KV binding)', () => {
40 it('round-trips a JSON value', async () => {
41 const value = { schema: { type: 'object' }, b: 2, a: [1, 2, 3] }
42 await putJson(env.SCHEMA_CACHE, 'test:round-trip', value)
43 expect(await getJson(env.SCHEMA_CACHE, 'test:round-trip')).toEqual(value)
44 })
45​
46 it('returns null for a missing key', async () => {
47 expect(await getJson(env.SCHEMA_CACHE, 'test:missing')).toBeNull()
48 })
49​
50 it('stores and retrieves by content hash', async () => {
51 const value = { type: 'object', properties: { model: { type: 'string' } } }
52 const hash = await putByHash(env.SCHEMA_CACHE, value)
53 expect(hash).toBe(await contentHash(value))
54 expect(await getByHash(env.SCHEMA_CACHE, hash)).toEqual(value)
55 expect(await getJson(env.SCHEMA_CACHE, schemaKey(hash))).toEqual(value)
56 })
57})