From a5326a67e37d9f1aee740f7b3d46345f3bcda419 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Wed, 9 Jul 2025 23:29:06 -0400 Subject: Factor data-to-JSON-string construction out of stitches. This is a recurring and nameable operation; let's give it a name before we use it further. --- ui/lib/swatch/json.test.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 ui/lib/swatch/json.test.js (limited to 'ui/lib/swatch/json.test.js') diff --git a/ui/lib/swatch/json.test.js b/ui/lib/swatch/json.test.js new file mode 100644 index 0000000..e01017d --- /dev/null +++ b/ui/lib/swatch/json.test.js @@ -0,0 +1,36 @@ +import * as json from './json.js'; +import { expect, describe, it } from 'vitest'; + +describe('encode', async () => { + it('converts atoms', async () => { + expect(json.encode(0)).toStrictEqual('0'); + expect(json.encode('hello')).toStrictEqual('"hello"'); + expect(json.encode(null)).toStrictEqual('null'); + expect(json.encode(true)).toStrictEqual('true'); + }); + + it('converts lists with indentation', async () => { + expect(json.encode([])).toStrictEqual('[]'); + expect(json.encode(['hello', 'world'])).toStrictEqual('[\n "hello",\n "world"\n]'); + }); + + it('converts objects with indentation', async () => { + expect(json.encode({})).toStrictEqual('{}'); + expect(json.encode({ field: 'value' })).toStrictEqual('{\n "field": "value"\n}'); + }); +}); + +describe('decode', async () => { + it('converts valid json values', async () => { + expect(json.decode('0')).toStrictEqual(0); + expect(json.decode('null')).toStrictEqual(null); + expect(json.decode('{}')).toStrictEqual({}); + expect(json.decode('[1, 2, "3"]')).toStrictEqual([1, 2, '3']); + }); + + it('converts invalid json to `undefined`', async () => { + expect(json.decode('')).toBeUndefined(); + expect(json.decode('{"foo":')).toBeUndefined(); + expect(json.decode('arbitrary nonsense')).toBeUndefined(); + }); +}); -- cgit v1.2.3