~james/core

core/web/src/lib/api/newsletter.test.ts -rw-r--r-- 1.5 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
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, vi } from "vitest";
import { signupNewsletter } from "#lib/api/newsletter.ts";
import type { Fetch } from "#lib/fetch.ts";

const respond = (status: number, body?: unknown) =>
	vi
		.fn<Fetch>()
		.mockResolvedValue(
			body === undefined ? new Response("", { status }) : Response.json(body, { status })
		);

describe("signupNewsletter", () => {
	it("posts the address to deliberi's open signup procedure", async () => {
		const fetchMock = respond(200);
		await signupNewsletter("https://deliberi.test/", "alice@example.com", fetchMock);

		const [url, init] = fetchMock.mock.calls[0];
		expect(String(url)).toBe("https://deliberi.test/xrpc/org.tangled.temp.newsletter.signup");
		expect(init?.method).toBe("POST");
		expect(new Headers(init?.headers).get("authorization")).toBeNull();
		expect(JSON.parse(String(init?.body))).toEqual({ email: "alice@example.com" });
	});

	it("tells a rejected address apart from a service failure", async () => {
		await expect(
			signupNewsletter(
				"https://deliberi.test",
				"nope",
				respond(400, { error: "InvalidEmail", message: "invalid email address" })
			)
		).rejects.toThrow("Enter a valid email address.");
		await expect(
			signupNewsletter("https://deliberi.test", "a@b.co", respond(502))
		).rejects.toThrow("Couldn't sign you up. Try again later.");
		await expect(
			signupNewsletter(
				"https://deliberi.test",
				"a@b.co",
				vi.fn<Fetch>().mockRejectedValue(new TypeError("offline"))
			)
		).rejects.toThrow("Couldn't sign you up. Try again later.");
	});
});