aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Effect/authCookie.test.ts
blob: bdcc4561146f636e14068313fd1de908cc1b5199 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { describe, expect, it } from "vitest";
import { Result } from "effect";
import {
	decodeAuthCookieEither,
	decodeAuthCookieOrNull,
	decodeAuthCookieOrThrow,
} from "$lib/Effect/authCookie";

describe("decodeAuthCookie", () => {
	it("decodes a valid user cookie payload", () => {
		const payload = JSON.stringify({
			token_type: "Bearer",
			expires_in: 3600,
			access_token: "access-token",
			refresh_token: "refresh-token",
		});
		const decoded = decodeAuthCookieEither(payload);

		expect(Result.isSuccess(decoded)).toBe(true);

		if (Result.isSuccess(decoded))
			expect(decoded.success).toEqual({
				tokenType: "Bearer",
				expiresIn: 3600,
				accessToken: "access-token",
				refreshToken: "refresh-token",
			});
	});

	it("returns a left when cookie JSON is invalid", () => {
		const decoded = decodeAuthCookieEither("{oops");

		expect(Result.isFailure(decoded)).toBe(true);
	});

	it("returns a left when required fields are missing", () => {
		const payload = JSON.stringify({
			token_type: "Bearer",
		});
		const decoded = decodeAuthCookieEither(payload);

		expect(Result.isFailure(decoded)).toBe(true);
	});

	it("throws on invalid payload through decodeAuthCookieOrThrow", () => {
		expect(() => decodeAuthCookieOrThrow("{oops")).toThrowError();
	});

	it("returns null on invalid payload through decodeAuthCookieOrNull", () => {
		expect(decodeAuthCookieOrNull("{oops")).toBeNull();
	});

	it("returns null for schema-valid but empty auth fields", () => {
		expect(
			decodeAuthCookieOrNull(
				JSON.stringify({
					token_type: "Bearer",
					expires_in: 3600,
					access_token: "",
					refresh_token: "",
				}),
			),
		).toBeNull();
	});
});