mirror of
https://github.com/multipleof4/ntfy.git
synced 2026-10-13 23:25:22 +00:00
Add basic JS tests
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
UnauthorizedError,
|
||||
UserExistsError,
|
||||
TopicReservedError,
|
||||
AccountActionLimitReachedError,
|
||||
IncorrectPasswordError,
|
||||
EmailVerificationCodeInvalidError,
|
||||
EmailPrimaryElsewhereError,
|
||||
throwAppError,
|
||||
fetchOrThrow,
|
||||
} from "./errors";
|
||||
|
||||
// A minimal stand-in for a fetch Response: just the bits errors.js reads.
|
||||
const fakeResponse = (status, body) => ({
|
||||
status,
|
||||
json: async () => {
|
||||
if (body === undefined) throw new Error("no body");
|
||||
return body;
|
||||
},
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
// errors.js logs to console.log on every error path; keep test output clean.
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("error classes", () => {
|
||||
it("carry the server error codes from errors.go", () => {
|
||||
expect(UserExistsError.CODE).toBe(40901);
|
||||
expect(TopicReservedError.CODE).toBe(40902);
|
||||
expect(AccountActionLimitReachedError.CODE).toBe(42906);
|
||||
expect(IncorrectPasswordError.CODE).toBe(40026);
|
||||
expect(EmailVerificationCodeInvalidError.CODE).toBe(40051);
|
||||
expect(EmailPrimaryElsewhereError.CODE).toBe(40908);
|
||||
});
|
||||
|
||||
it("are Error subclasses with human-readable messages", () => {
|
||||
expect(new UnauthorizedError()).toBeInstanceOf(Error);
|
||||
expect(new UnauthorizedError().message).toBe("Unauthorized");
|
||||
expect(new UserExistsError().message).toBe("Username already exists");
|
||||
});
|
||||
});
|
||||
|
||||
describe("throwAppError", () => {
|
||||
it("maps 401 and 403 to UnauthorizedError", async () => {
|
||||
await expect(throwAppError(fakeResponse(401))).rejects.toBeInstanceOf(UnauthorizedError);
|
||||
await expect(throwAppError(fakeResponse(403))).rejects.toBeInstanceOf(UnauthorizedError);
|
||||
});
|
||||
|
||||
it("maps known ntfy error codes to their specific error classes", async () => {
|
||||
await expect(throwAppError(fakeResponse(409, { code: UserExistsError.CODE }))).rejects.toBeInstanceOf(UserExistsError);
|
||||
await expect(throwAppError(fakeResponse(409, { code: TopicReservedError.CODE }))).rejects.toBeInstanceOf(TopicReservedError);
|
||||
await expect(throwAppError(fakeResponse(429, { code: AccountActionLimitReachedError.CODE }))).rejects.toBeInstanceOf(
|
||||
AccountActionLimitReachedError
|
||||
);
|
||||
});
|
||||
|
||||
it("wraps an unknown code that carries an error message in a generic Error", async () => {
|
||||
await expect(throwAppError(fakeResponse(400, { code: 12345, error: "boom" }))).rejects.toThrow("Error 12345: boom");
|
||||
});
|
||||
|
||||
it("throws a generic 'Unexpected response' error when there is no ntfy error body", async () => {
|
||||
await expect(throwAppError(fakeResponse(500))).rejects.toThrow("Unexpected response 500");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchOrThrow", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("returns the response unchanged on HTTP 200", async () => {
|
||||
const response = { status: 200 };
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => response)
|
||||
);
|
||||
await expect(fetchOrThrow("https://ntfy.sh/mytopic/json")).resolves.toBe(response);
|
||||
});
|
||||
|
||||
it("throws on a non-200 response", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => fakeResponse(401))
|
||||
);
|
||||
await expect(fetchOrThrow("https://ntfy.sh/mytopic/json")).rejects.toBeInstanceOf(UnauthorizedError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import emojisMapped from "./emojisMapped";
|
||||
import { formatTitle, formatMessage, isImage, notificationTag, toNotificationParams, messageWithSequenceId } from "./notificationUtils";
|
||||
|
||||
// Pick a real alias/emoji pair so we don't hardcode a specific glyph that could change upstream.
|
||||
const [emojiAlias, emojiChar] = Object.entries(emojisMapped)[0];
|
||||
|
||||
describe("formatTitle", () => {
|
||||
it("returns the bare title when there are no emoji tags", () => {
|
||||
expect(formatTitle({ title: "Hello", tags: ["not-an-emoji"] })).toBe("Hello");
|
||||
expect(formatTitle({ title: "Hello" })).toBe("Hello");
|
||||
});
|
||||
|
||||
it("prepends mapped emoji for emoji tags", () => {
|
||||
expect(formatTitle({ title: "Hello", tags: [emojiAlias] })).toBe(`${emojiChar} Hello`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMessage", () => {
|
||||
it("returns the message untouched when the notification has a title", () => {
|
||||
expect(formatMessage({ title: "T", message: "Body", tags: [emojiAlias] })).toBe("Body");
|
||||
});
|
||||
|
||||
it("prepends emoji to the message when there is no title", () => {
|
||||
expect(formatMessage({ message: "Body", tags: [emojiAlias] })).toBe(`${emojiChar} Body`);
|
||||
});
|
||||
|
||||
it("falls back to an empty string when message is missing", () => {
|
||||
expect(formatMessage({})).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isImage", () => {
|
||||
it("trusts an explicit image MIME type", () => {
|
||||
expect(isImage({ type: "image/png", name: "whatever.txt" })).toBe(true);
|
||||
expect(isImage({ type: "application/pdf", name: "x.png" })).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the file extension when there is no type", () => {
|
||||
expect(isImage({ name: "photo.JPEG" })).toBeTruthy();
|
||||
expect(isImage({ url: "https://ntfy.sh/file/x.webp" })).toBeTruthy();
|
||||
expect(isImage({ name: "notes.txt" })).toBeFalsy();
|
||||
});
|
||||
|
||||
it("returns false for a missing attachment", () => {
|
||||
expect(isImage(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("notificationTag", () => {
|
||||
it("scopes the tag by baseUrl, topic and sequence id", () => {
|
||||
expect(notificationTag("https://ntfy.sh", "mytopic", 42)).toBe("https://ntfy.sh/mytopic/42");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toNotificationParams", () => {
|
||||
const baseMessage = {
|
||||
id: "msg-1",
|
||||
time: 1700000000,
|
||||
title: "Title",
|
||||
message: "Body",
|
||||
actions: [
|
||||
{ action: "view", label: "Open" },
|
||||
{ action: "http", label: "Send" },
|
||||
{ action: "broadcast", label: "Cast" },
|
||||
],
|
||||
};
|
||||
|
||||
it("builds the [title, options] tuple consumed by the Notifications API", () => {
|
||||
const [title, options] = toNotificationParams({
|
||||
message: baseMessage,
|
||||
defaultTitle: "fallback",
|
||||
topicRoute: "/mytopic",
|
||||
baseUrl: "https://ntfy.sh",
|
||||
topic: "mytopic",
|
||||
});
|
||||
|
||||
expect(title).toBe("Title");
|
||||
expect(options.body).toBe("Body");
|
||||
expect(options.tag).toBe("https://ntfy.sh/mytopic/msg-1");
|
||||
expect(options.timestamp).toBe(baseMessage.time * 1000);
|
||||
expect(options.data.subscriptionId).toBe("https://ntfy.sh/mytopic");
|
||||
expect(options.data.topicRoute).toBe("/mytopic");
|
||||
});
|
||||
|
||||
it("keeps only view/http actions and maps them to {action,title}", () => {
|
||||
const [, options] = toNotificationParams({
|
||||
message: baseMessage,
|
||||
defaultTitle: "fallback",
|
||||
topicRoute: "/mytopic",
|
||||
baseUrl: "https://ntfy.sh",
|
||||
topic: "mytopic",
|
||||
});
|
||||
expect(options.actions).toEqual([
|
||||
{ action: "Open", title: "Open" },
|
||||
{ action: "Send", title: "Send" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses the default title when the message has none", () => {
|
||||
const [title] = toNotificationParams({
|
||||
message: { id: "x", time: 1, message: "Body" },
|
||||
defaultTitle: "fallback",
|
||||
topicRoute: "/mytopic",
|
||||
baseUrl: "https://ntfy.sh",
|
||||
topic: "mytopic",
|
||||
});
|
||||
expect(title).toBe("fallback");
|
||||
});
|
||||
|
||||
it("prefers sequence_id over id for the notification tag", () => {
|
||||
const [, options] = toNotificationParams({
|
||||
message: { ...baseMessage, sequence_id: 99 },
|
||||
defaultTitle: "fallback",
|
||||
topicRoute: "/mytopic",
|
||||
baseUrl: "https://ntfy.sh",
|
||||
topic: "mytopic",
|
||||
});
|
||||
expect(options.tag).toBe("https://ntfy.sh/mytopic/99");
|
||||
});
|
||||
});
|
||||
|
||||
describe("messageWithSequenceId", () => {
|
||||
it("derives sequenceId from sequence_id when absent", () => {
|
||||
expect(messageWithSequenceId({ id: "a", sequence_id: 7 }).sequenceId).toBe(7);
|
||||
});
|
||||
|
||||
it("falls back to id when sequence_id is missing", () => {
|
||||
expect(messageWithSequenceId({ id: "a" }).sequenceId).toBe("a");
|
||||
});
|
||||
|
||||
it("returns the message unchanged when sequenceId already set", () => {
|
||||
const m = { id: "a", sequenceId: 1 };
|
||||
expect(messageWithSequenceId(m)).toBe(m);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { THEME } from "./Prefs";
|
||||
import {
|
||||
topicUrl,
|
||||
topicUrlWs,
|
||||
topicUrlJsonPollWithSince,
|
||||
accountUrl,
|
||||
accountTokenUrl,
|
||||
shortUrl,
|
||||
expandUrl,
|
||||
expandSecureUrl,
|
||||
validUrl,
|
||||
validTopic,
|
||||
disallowedTopic,
|
||||
encodeBase64,
|
||||
encodeBase64Url,
|
||||
bearerAuth,
|
||||
basicAuth,
|
||||
withBearerAuth,
|
||||
maybeWithAuth,
|
||||
splitNoEmpty,
|
||||
hashCode,
|
||||
formatBytes,
|
||||
formatNumber,
|
||||
formatPrice,
|
||||
formatShortDuration,
|
||||
getKebabCaseLangStr,
|
||||
darkModeEnabled,
|
||||
urlB64ToUint8Array,
|
||||
} from "./utils";
|
||||
|
||||
describe("URL builders", () => {
|
||||
it("build topic URLs", () => {
|
||||
expect(topicUrl("https://ntfy.sh", "mytopic")).toBe("https://ntfy.sh/mytopic");
|
||||
expect(topicUrlJsonPollWithSince("https://ntfy.sh", "mytopic", 123)).toBe("https://ntfy.sh/mytopic/json?poll=1&since=123");
|
||||
});
|
||||
|
||||
it("rewrite the scheme for websocket URLs", () => {
|
||||
expect(topicUrlWs("https://ntfy.sh", "mytopic")).toBe("wss://ntfy.sh/mytopic/ws");
|
||||
expect(topicUrlWs("http://localhost:8080", "mytopic")).toBe("ws://localhost:8080/mytopic/ws");
|
||||
});
|
||||
|
||||
it("build account URLs", () => {
|
||||
expect(accountUrl("https://ntfy.sh")).toBe("https://ntfy.sh/v1/account");
|
||||
expect(accountTokenUrl("https://ntfy.sh")).toBe("https://ntfy.sh/v1/account/token");
|
||||
});
|
||||
});
|
||||
|
||||
describe("url helpers", () => {
|
||||
it("strip the scheme with shortUrl", () => {
|
||||
expect(shortUrl("https://ntfy.sh/mytopic")).toBe("ntfy.sh/mytopic");
|
||||
});
|
||||
|
||||
it("expand a bare host to both schemes", () => {
|
||||
expect(expandUrl("ntfy.sh")).toEqual(["https://ntfy.sh", "http://ntfy.sh"]);
|
||||
expect(expandSecureUrl("ntfy.sh")).toBe("https://ntfy.sh");
|
||||
});
|
||||
|
||||
it("validate http(s) URLs", () => {
|
||||
expect(validUrl("https://ntfy.sh")).toBeTruthy();
|
||||
expect(validUrl("http://ntfy.sh")).toBeTruthy();
|
||||
expect(validUrl("ftp://ntfy.sh")).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("topic validation", () => {
|
||||
it("rejects disallowed topics (from config.disallowed_topics)", () => {
|
||||
expect(disallowedTopic("app")).toBe(true);
|
||||
expect(disallowedTopic("mytopic")).toBe(false);
|
||||
expect(validTopic("app")).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts well-formed topic names and rejects malformed ones", () => {
|
||||
expect(validTopic("valid_Topic-123")).toBeTruthy();
|
||||
expect(validTopic("bad/slash")).toBeFalsy();
|
||||
expect(validTopic("with space")).toBeFalsy();
|
||||
expect(validTopic("")).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("base64 + auth headers", () => {
|
||||
it("encodes base64 and base64url", () => {
|
||||
expect(encodeBase64("hello")).toBe("aGVsbG8=");
|
||||
expect(encodeBase64Url("hello")).toBe("aGVsbG8");
|
||||
});
|
||||
|
||||
it("builds bearer and basic auth headers", () => {
|
||||
expect(bearerAuth("tok")).toBe("Bearer tok");
|
||||
expect(basicAuth("phil", "secret")).toBe(`Basic ${encodeBase64("phil:secret")}`);
|
||||
expect(withBearerAuth({ "Content-Type": "application/json" }, "tok")).toEqual({
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer tok",
|
||||
});
|
||||
});
|
||||
|
||||
it("picks the right scheme in maybeWithAuth", () => {
|
||||
expect(maybeWithAuth({}, { username: "u", password: "p" }).Authorization).toBe(basicAuth("u", "p"));
|
||||
expect(maybeWithAuth({}, { token: "tok" }).Authorization).toBe(bearerAuth("tok"));
|
||||
expect(maybeWithAuth({ a: 1 }, undefined)).toEqual({ a: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("misc pure helpers", () => {
|
||||
it("splitNoEmpty trims and drops empty entries", () => {
|
||||
expect(splitNoEmpty("a, b, ,c ", ",")).toEqual(["a", "b", "c"]);
|
||||
expect(splitNoEmpty("", ",")).toEqual([]);
|
||||
});
|
||||
|
||||
it("hashCode is deterministic", () => {
|
||||
expect(hashCode("")).toBe(0);
|
||||
expect(hashCode("a")).toBe(97);
|
||||
expect(hashCode("hello")).toBe(hashCode("hello"));
|
||||
});
|
||||
|
||||
it("formatBytes is human readable", () => {
|
||||
expect(formatBytes(0)).toBe("0 bytes");
|
||||
expect(formatBytes(1024)).toBe("1 KB");
|
||||
expect(formatBytes(1536)).toBe("1.5 KB");
|
||||
});
|
||||
|
||||
it("formatNumber abbreviates round thousands", () => {
|
||||
expect(formatNumber(0)).toBe(0);
|
||||
expect(formatNumber(1000)).toBe("1k");
|
||||
expect(formatNumber(1500)).toBe((1500).toLocaleString());
|
||||
});
|
||||
|
||||
it("formatPrice renders cents as dollars", () => {
|
||||
expect(formatPrice(100)).toBe("$1");
|
||||
expect(formatPrice(150)).toBe("$1.5");
|
||||
});
|
||||
|
||||
it("formatShortDuration picks the largest fitting unit", () => {
|
||||
expect(formatShortDuration(60000, "en")).toContain("minute");
|
||||
expect(formatShortDuration(3600000, "en")).toContain("hour");
|
||||
});
|
||||
|
||||
it("getKebabCaseLangStr normalizes language tags", () => {
|
||||
expect(getKebabCaseLangStr("en_US")).toBe("en-US");
|
||||
expect(getKebabCaseLangStr(undefined)).toBe("en");
|
||||
expect(getKebabCaseLangStr("")).toBe("en");
|
||||
});
|
||||
|
||||
it("darkModeEnabled honors the theme preference", () => {
|
||||
expect(darkModeEnabled(false, THEME.DARK)).toBe(true);
|
||||
expect(darkModeEnabled(true, THEME.LIGHT)).toBe(false);
|
||||
expect(darkModeEnabled(true, THEME.SYSTEM)).toBe(true);
|
||||
expect(darkModeEnabled(false, THEME.SYSTEM)).toBe(false);
|
||||
});
|
||||
|
||||
it("urlB64ToUint8Array decodes web push keys", () => {
|
||||
expect(Array.from(urlB64ToUint8Array("AQID"))).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
/* eslint-env node, es2021 */
|
||||
// Minimal window stub so the pure-logic modules import cleanly under the node environment,
|
||||
// without pulling in jsdom. utils.js -> config.js does `const { config } = window;` at import
|
||||
// time, and config.js falls back to window.location.origin when base_url is empty.
|
||||
globalThis.window = {
|
||||
location: { origin: "https://ntfy.sh" },
|
||||
config: { base_url: "", disallowed_topics: ["app", "account", "settings"] },
|
||||
atob: globalThis.atob, // urlB64ToUint8Array uses window.atob; Node provides global atob
|
||||
};
|
||||
|
||||
// utils.js -> Prefs.js -> db.js -> Session.username() reads localStorage at module load.
|
||||
// Node has no localStorage; an in-memory stand-in is enough for the pure-logic tests.
|
||||
const store = new Map();
|
||||
globalThis.localStorage = {
|
||||
getItem: (key) => (store.has(key) ? store.get(key) : null),
|
||||
setItem: (key, value) => store.set(key, String(value)),
|
||||
removeItem: (key) => store.delete(key),
|
||||
clear: () => store.clear(),
|
||||
};
|
||||
Reference in New Issue
Block a user