aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Effect/json.test.ts
blob: c13824fef90953238a75ffa36280f0c1b503bd10 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { describe, expect, it } from "vitest";
import {
	parseJsonStringOrDefault,
	parseJsonStringOrThrow,
	parseJsonStringWithSchemaOrDefault,
} from "$lib/Effect/json";
import { Schema } from "effect";

describe("effect json parsing", () => {
	it("parses valid json strings", () => {
		expect(parseJsonStringOrThrow(`{"ok":true,"value":3}`)).toEqual({
			ok: true,
			value: 3,
		});
	});

	it("throws for invalid json strings", () => {
		expect(() => parseJsonStringOrThrow("{nope}")).toThrowError();
	});

	it("returns fallback for invalid json", () => {
		expect(parseJsonStringOrDefault("{nope}", { ok: false })).toEqual({
			ok: false,
		});
	});

	it("decodes json with a schema and returns fallback on schema mismatch", () => {
		expect(
			parseJsonStringWithSchemaOrDefault(
				"[1,2,3]",
				Schema.Array(Schema.Number),
				[],
			),
		).toEqual([1, 2, 3]);
		expect(
			parseJsonStringWithSchemaOrDefault(
				`["a",2]`,
				Schema.Array(Schema.Number),
				[],
			),
		).toEqual([]);
	});
});