mirror of
https://github.com/mediacms-io/mediacms.git
synced 2026-01-20 15:22:58 -05:00
feat: frontend unit tests
This commit is contained in:
56
frontend/tests/utils/helpers/csrfToken.test.ts
Normal file
56
frontend/tests/utils/helpers/csrfToken.test.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { csrfToken } from '../../../src/static/js/utils/helpers/csrfToken';
|
||||
|
||||
const setupDocumentCookie = () => {
|
||||
if (typeof document === 'undefined') {
|
||||
globalThis.document = { cookie: '' } as unknown as Document;
|
||||
}
|
||||
};
|
||||
|
||||
const setDocumentCookie = (value: string) => {
|
||||
if (typeof document !== 'undefined') {
|
||||
Object.defineProperty(document, 'cookie', { value, writable: true, configurable: true });
|
||||
}
|
||||
};
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('csrfToken', () => {
|
||||
const originalCookie = document.cookie;
|
||||
|
||||
beforeAll(() => {
|
||||
// Initialize document environment
|
||||
setupDocumentCookie();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original cookie string
|
||||
setDocumentCookie(originalCookie);
|
||||
});
|
||||
|
||||
test('Returns null when document.cookie is empty', () => {
|
||||
setDocumentCookie('');
|
||||
expect(csrfToken()).toBeNull();
|
||||
});
|
||||
|
||||
test('Returns null when csrftoken is not present', () => {
|
||||
setDocumentCookie('sessionid=abc; theme=dark');
|
||||
expect(csrfToken()).toBeNull();
|
||||
});
|
||||
|
||||
test('Finds and decodes the csrftoken cookie value', () => {
|
||||
const token = encodeURIComponent('a b+c%20');
|
||||
setDocumentCookie(`sessionid=abc; csrftoken=${token}; theme=dark`);
|
||||
expect(csrfToken()).toBe('a b+c%20');
|
||||
});
|
||||
|
||||
test('Ignores leading spaces and matches exact prefix csrftoken=', () => {
|
||||
setDocumentCookie(' sessionid=xyz; csrftoken=secure123; other=value');
|
||||
expect(csrfToken()).toBe('secure123');
|
||||
});
|
||||
|
||||
test('Stops scanning once csrftoken is found', () => {
|
||||
// Ensure csrftoken occurs before other long tail cookies
|
||||
setDocumentCookie('csrftoken=first; a=1; b=2; c=3; d=4; e=5');
|
||||
expect(csrfToken()).toBe('first');
|
||||
});
|
||||
});
|
||||
});
|
||||
220
frontend/tests/utils/helpers/dom.test.ts
Normal file
220
frontend/tests/utils/helpers/dom.test.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import {
|
||||
supportsSvgAsImg,
|
||||
removeClassname,
|
||||
addClassname,
|
||||
hasClassname,
|
||||
BrowserEvents,
|
||||
} from '../../../src/static/js/utils/helpers/dom';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
mozRequestAnimationFrame?: Window['requestAnimationFrame'];
|
||||
webkitRequestAnimationFrame?: Window['requestAnimationFrame'];
|
||||
msRequestAnimationFrame?: Window['requestAnimationFrame'];
|
||||
mozCancelAnimationFrame?: Window['cancelAnimationFrame'];
|
||||
}
|
||||
}
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('dom', () => {
|
||||
describe('supportsSvgAsImg', () => {
|
||||
test('Delegates to document.implementation.hasFeature', () => {
|
||||
const spy = jest.spyOn(document.implementation as any, 'hasFeature').mockReturnValueOnce(true);
|
||||
expect(supportsSvgAsImg()).toBe(true);
|
||||
expect(spy).toHaveBeenCalledWith('http://www.w3.org/TR/SVG11/feature#Image', '1.1');
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
test('Returns false when feature detection fails', () => {
|
||||
const spy = jest.spyOn(document.implementation as any, 'hasFeature').mockReturnValueOnce(false);
|
||||
expect(supportsSvgAsImg()).toBe(false);
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('BrowserEvents', () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(document, 'addEventListener').mockClear();
|
||||
jest.spyOn(window, 'addEventListener').mockClear();
|
||||
document.addEventListener = jest.fn();
|
||||
window.addEventListener = jest.fn();
|
||||
});
|
||||
|
||||
test('Registers global listeners on construction and invokes callbacks on events', () => {
|
||||
const be = BrowserEvents();
|
||||
|
||||
const visCb = jest.fn();
|
||||
const resizeCb = jest.fn();
|
||||
const scrollCb = jest.fn();
|
||||
|
||||
// Register callbacks
|
||||
be.doc(visCb);
|
||||
be.win(resizeCb, scrollCb);
|
||||
|
||||
// Capture the callback passed to addEventListener for each event
|
||||
const docHandler = (document.addEventListener as jest.Mock).mock.calls.find(
|
||||
(c) => c[0] === 'visibilitychange'
|
||||
)?.[1] as Function;
|
||||
|
||||
const resizeHandler = (window.addEventListener as jest.Mock).mock.calls.find(
|
||||
(c) => c[0] === 'resize'
|
||||
)?.[1] as Function;
|
||||
|
||||
const scrollHandler = (window.addEventListener as jest.Mock).mock.calls.find(
|
||||
(c) => c[0] === 'scroll'
|
||||
)?.[1] as Function;
|
||||
|
||||
// Fire handlers to simulate events
|
||||
docHandler();
|
||||
resizeHandler();
|
||||
scrollHandler();
|
||||
|
||||
expect(visCb).toHaveBeenCalledTimes(1);
|
||||
expect(resizeCb).toHaveBeenCalledTimes(1);
|
||||
expect(scrollCb).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// @todo: Revisit this behavior
|
||||
test('Does not register non-function callbacks', () => {
|
||||
const be = BrowserEvents();
|
||||
|
||||
be.win('not-a-fn', null);
|
||||
be.doc(undefined);
|
||||
|
||||
// Should still have registered the listeners on construction
|
||||
expect(
|
||||
(document.addEventListener as jest.Mock).mock.calls.some((c) => c[0] === 'visibilitychange')
|
||||
).toBe(true);
|
||||
expect((window.addEventListener as jest.Mock).mock.calls.some((c) => c[0] === 'resize')).toBe(true);
|
||||
expect((window.addEventListener as jest.Mock).mock.calls.some((c) => c[0] === 'scroll')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BrowserEvents (edge cases)', () => {
|
||||
beforeEach(() => {
|
||||
(document.addEventListener as jest.Mock).mockClear();
|
||||
(window.addEventListener as jest.Mock).mockClear();
|
||||
document.addEventListener = jest.fn();
|
||||
window.addEventListener = jest.fn();
|
||||
});
|
||||
|
||||
test('Multiple callbacks are invoked in order for each event type', () => {
|
||||
const be = BrowserEvents();
|
||||
|
||||
const v1 = jest.fn();
|
||||
const v2 = jest.fn();
|
||||
const r1 = jest.fn();
|
||||
const r2 = jest.fn();
|
||||
const s1 = jest.fn();
|
||||
const s2 = jest.fn();
|
||||
|
||||
be.doc(v1);
|
||||
be.doc(v2);
|
||||
be.win(r1, s1);
|
||||
be.win(r2, s2);
|
||||
|
||||
const docHandler = (document.addEventListener as jest.Mock).mock.calls.find(
|
||||
(c) => c[0] === 'visibilitychange'
|
||||
)?.[1] as Function;
|
||||
|
||||
const resizeHandler = (window.addEventListener as jest.Mock).mock.calls.find(
|
||||
(c) => c[0] === 'resize'
|
||||
)?.[1] as Function;
|
||||
|
||||
const scrollHandler = (window.addEventListener as jest.Mock).mock.calls.find(
|
||||
(c) => c[0] === 'scroll'
|
||||
)?.[1] as Function;
|
||||
|
||||
// Fire events twice to ensure each call triggers callbacks once per firing
|
||||
docHandler();
|
||||
resizeHandler();
|
||||
scrollHandler();
|
||||
|
||||
docHandler();
|
||||
resizeHandler();
|
||||
scrollHandler();
|
||||
|
||||
expect(v1).toHaveBeenCalledTimes(2);
|
||||
expect(v2).toHaveBeenCalledTimes(2);
|
||||
expect(r1).toHaveBeenCalledTimes(2);
|
||||
expect(r2).toHaveBeenCalledTimes(2);
|
||||
expect(s1).toHaveBeenCalledTimes(2);
|
||||
expect(s2).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Ensure order of invocation within each firing respects registration order
|
||||
// Jest mock call order grows monotonically; validate the first calls were in the expected sequence
|
||||
expect(v1.mock.invocationCallOrder[0]).toBeLessThan(v2.mock.invocationCallOrder[0]);
|
||||
expect(r1.mock.invocationCallOrder[0]).toBeLessThan(r2.mock.invocationCallOrder[0]);
|
||||
expect(s1.mock.invocationCallOrder[0]).toBeLessThan(s2.mock.invocationCallOrder[0]);
|
||||
});
|
||||
|
||||
// @todo: Check again this behavior
|
||||
test('Ignores non-function values without throwing and still registers listeners once', () => {
|
||||
const be = BrowserEvents();
|
||||
|
||||
be.doc('noop');
|
||||
be.win(null, undefined);
|
||||
|
||||
const docCount = (document.addEventListener as jest.Mock).mock.calls.filter(
|
||||
(c) => c[0] === 'visibilitychange'
|
||||
).length;
|
||||
const resizeCount = (window.addEventListener as jest.Mock).mock.calls.filter(
|
||||
(c) => c[0] === 'resize'
|
||||
).length;
|
||||
const scrollCount = (window.addEventListener as jest.Mock).mock.calls.filter(
|
||||
(c) => c[0] === 'scroll'
|
||||
).length;
|
||||
|
||||
expect(docCount).toBe(1);
|
||||
expect(resizeCount).toBe(1);
|
||||
expect(scrollCount).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('classname helpers', () => {
|
||||
test('addClassname uses classList.add when available', () => {
|
||||
const el = document.createElement('div') as any;
|
||||
const mockAdd = jest.fn();
|
||||
el.classList.add = mockAdd;
|
||||
|
||||
addClassname(el, 'active');
|
||||
expect(mockAdd).toHaveBeenCalledWith('active');
|
||||
});
|
||||
|
||||
test('removeClassname uses classList.remove when available', () => {
|
||||
const el = document.createElement('div') as any;
|
||||
const mockRemove = jest.fn();
|
||||
el.classList.remove = mockRemove;
|
||||
removeClassname(el, 'active');
|
||||
expect(mockRemove).toHaveBeenCalledWith('active');
|
||||
});
|
||||
|
||||
test('addClassname fallback appends class to className', () => {
|
||||
const el = document.createElement('div') as any;
|
||||
el.className = 'one';
|
||||
// Remove classList to test fallback behavior
|
||||
delete el.classList;
|
||||
addClassname(el, 'two');
|
||||
expect(el.className).toBe('one two');
|
||||
});
|
||||
|
||||
test('removeClassname fallback removes class via regex', () => {
|
||||
const el = document.createElement('div') as any;
|
||||
el.className = 'one two three two';
|
||||
// Remove classList to test fallback behavior
|
||||
delete el.classList;
|
||||
removeClassname(el, 'two');
|
||||
// The regex replacement may leave extra spaces
|
||||
expect(el.className.replaceAll(/\s+/g, ' ').trim()).toBe('one three');
|
||||
});
|
||||
|
||||
test('hasClassname checks for exact class match boundaries', () => {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'one two-three';
|
||||
expect(hasClassname(el, 'one')).toBe(true);
|
||||
expect(hasClassname(el, 'two')).toBe(false); // Should not match within two-three
|
||||
expect(hasClassname(el, 'two-three')).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
47
frontend/tests/utils/helpers/errors.test.ts
Normal file
47
frontend/tests/utils/helpers/errors.test.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
// Mock the './log' module used by errors.ts to capture calls without console side effects
|
||||
jest.mock('../../../src/static/js/utils/helpers/log', () => ({ error: jest.fn(), warn: jest.fn() }));
|
||||
|
||||
import { logErrorAndReturnError, logWarningAndReturnError } from '../../../src/static/js/utils/helpers/errors';
|
||||
import { error as mockedError, warn as mockedWarn } from '../../../src/static/js/utils/helpers/log';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('errors', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
test('logErrorAndReturnError returns Error with first message and logs with error', () => {
|
||||
const messages = ['Primary msg', 'details', 'more'];
|
||||
const err = logErrorAndReturnError(messages);
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('Primary msg');
|
||||
expect(mockedError).toHaveBeenCalledTimes(1);
|
||||
expect(mockedError).toHaveBeenCalledWith(...messages);
|
||||
});
|
||||
|
||||
test('logWarningAndReturnError returns Error with first message and logs with warn', () => {
|
||||
const messages = ['Primary msg', 'details', 'more'];
|
||||
const err = logWarningAndReturnError(messages);
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('Primary msg');
|
||||
expect(mockedWarn).toHaveBeenCalledTimes(1);
|
||||
expect(mockedWarn).toHaveBeenCalledWith(...messages);
|
||||
});
|
||||
|
||||
test('Handles empty array creating an Error with undefined message and logs called with no args', () => {
|
||||
const messages: string[] = [];
|
||||
|
||||
const err1 = logErrorAndReturnError(messages);
|
||||
expect(err1).toBeInstanceOf(Error);
|
||||
expect(err1.message).toBe('');
|
||||
expect(mockedError).toHaveBeenCalledWith('');
|
||||
|
||||
jest.clearAllMocks();
|
||||
|
||||
const err2 = logWarningAndReturnError(messages);
|
||||
expect(err2).toBeInstanceOf(Error);
|
||||
expect(err2.message).toBe('');
|
||||
expect(mockedWarn).toHaveBeenCalledWith('');
|
||||
});
|
||||
});
|
||||
});
|
||||
44
frontend/tests/utils/helpers/exportStore.test.ts
Normal file
44
frontend/tests/utils/helpers/exportStore.test.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// Mock the dispatcher module used by exportStore
|
||||
jest.mock('../../../src/static/js/utils/dispatcher', () => ({ register: jest.fn() }));
|
||||
|
||||
import exportStore from '../../../src/static/js/utils/helpers/exportStore';
|
||||
|
||||
// Re-import the mocked dispatcher for assertions
|
||||
import * as dispatcher from '../../../src/static/js/utils/dispatcher';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('exportStore', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
test('Registers store handler with dispatcher and binds context', () => {
|
||||
const ctx: { value: number; inc?: () => void } = { value: 0 };
|
||||
const handlerName = 'inc';
|
||||
const handler = function (this: typeof ctx) {
|
||||
this.value += 1;
|
||||
};
|
||||
ctx[handlerName] = handler as any;
|
||||
|
||||
const result = exportStore(ctx, handlerName);
|
||||
|
||||
// returns the same store instance
|
||||
expect(result).toBe(ctx);
|
||||
|
||||
// Ensure dispatcher.register was called once with a bound function
|
||||
expect((dispatcher as any).register).toHaveBeenCalledTimes(1);
|
||||
const registeredFn = (dispatcher as any).register.mock.calls[0][0] as Function;
|
||||
expect(typeof registeredFn).toBe('function');
|
||||
|
||||
// Verify the registered function is bound to the store context
|
||||
registeredFn();
|
||||
expect(ctx.value).toBe(1);
|
||||
});
|
||||
|
||||
test('Throws if handler name does not exist on store', () => {
|
||||
const store: any = {};
|
||||
// Accessing store[handler] would be undefined; calling .bind on undefined would throw
|
||||
expect(() => exportStore(store, 'missing')).toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
23
frontend/tests/utils/helpers/formatInnerLink.test.ts
Normal file
23
frontend/tests/utils/helpers/formatInnerLink.test.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { formatInnerLink } from '../../../src/static/js/utils/helpers/formatInnerLink';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('formatInnerLink', () => {
|
||||
test('Returns the same absolute URL unchanged', () => {
|
||||
const url = 'https://example.com/path?x=1#hash';
|
||||
const base = 'https://base.example.org';
|
||||
expect(formatInnerLink(url, base)).toBe(url);
|
||||
});
|
||||
|
||||
test('Constructs absolute URL from relative path with leading slash', () => {
|
||||
const url = '/images/picture.png';
|
||||
const base = 'https://media.example.com';
|
||||
expect(formatInnerLink(url, base)).toBe('https://media.example.com/images/picture.png');
|
||||
});
|
||||
|
||||
test('Constructs absolute URL from relative path without leading slash', () => {
|
||||
const url = 'assets/file.txt';
|
||||
const base = 'https://cdn.example.com';
|
||||
expect(formatInnerLink(url, base)).toBe('https://cdn.example.com/assets/file.txt');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { formatManagementTableDate } from '../../../src/static/js/utils/helpers/formatManagementTableDate';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('formatManagementTableDate', () => {
|
||||
test('Formats date with zero-padded time components', () => {
|
||||
const d = new Date(2021, 0, 5, 3, 7, 9); // Jan=0, day 5, 03:07:09
|
||||
expect(formatManagementTableDate(d)).toBe('Jan 5, 2021 03:07:09');
|
||||
});
|
||||
|
||||
test('Formats date with double-digit time components and month abbreviation', () => {
|
||||
const d = new Date(1999, 11, 31, 23, 59, 58); // Dec=11
|
||||
expect(formatManagementTableDate(d)).toBe('Dec 31, 1999 23:59:58');
|
||||
});
|
||||
});
|
||||
});
|
||||
106
frontend/tests/utils/helpers/formatViewsNumber.test.ts
Normal file
106
frontend/tests/utils/helpers/formatViewsNumber.test.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import formatViewsNumber from '../../../src/static/js/utils/helpers/formatViewsNumber';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('formatViewsNumber', () => {
|
||||
describe('fullNumber = false (default compact formatting)', () => {
|
||||
test('Formats values < 1,000 without suffix and with correct rounding', () => {
|
||||
expect(formatViewsNumber(0)).toBe('0');
|
||||
expect(formatViewsNumber(9)).toBe('9');
|
||||
expect(formatViewsNumber(12)).toBe('12');
|
||||
expect(formatViewsNumber(999)).toBe('999');
|
||||
});
|
||||
|
||||
test('Formats thousands to K with decimals for < 10K and none for >= 10K', () => {
|
||||
expect(formatViewsNumber(1000)).toBe('1K');
|
||||
expect(formatViewsNumber(1500)).toBe('1.5K');
|
||||
expect(formatViewsNumber(1499)).toBe('1.5K'); // rounds to 1 decimal
|
||||
expect(formatViewsNumber(10_000)).toBe('10K');
|
||||
expect(formatViewsNumber(10_400)).toBe('10K');
|
||||
expect(formatViewsNumber(10_500)).toBe('11K'); // rounds to nearest whole
|
||||
expect(formatViewsNumber(99_900)).toBe('100K'); // rounding up
|
||||
});
|
||||
|
||||
test('Formats millions to M with decimals for < 10M and none for >= 10M', () => {
|
||||
expect(formatViewsNumber(1_000_000)).toBe('1M');
|
||||
expect(formatViewsNumber(1_200_000)).toBe('1.2M');
|
||||
expect(formatViewsNumber(9_440_000)).toBe('9.4M');
|
||||
expect(formatViewsNumber(9_960_000)).toBe('10M'); // rounds to whole when >= 10M threshold after rounding
|
||||
expect(formatViewsNumber(10_000_000)).toBe('10M');
|
||||
});
|
||||
|
||||
test('Formats billions and trillions correctly', () => {
|
||||
expect(formatViewsNumber(1_000_000_000)).toBe('1B');
|
||||
expect(formatViewsNumber(1_500_000_000)).toBe('1.5B');
|
||||
expect(formatViewsNumber(10_000_000_000)).toBe('10B');
|
||||
expect(formatViewsNumber(1_000_000_000_000)).toBe('1T');
|
||||
expect(formatViewsNumber(1_230_000_000_000)).toBe('1.2T');
|
||||
});
|
||||
|
||||
// @todo: Revisit this behavior
|
||||
test('Beyond last unit keeps using the last unit with scaling', () => {
|
||||
// Implementation scales beyond units by increasing the value so that the last unit remains applicable
|
||||
// Here, expect a number in T with rounding behavior similar to others
|
||||
expect(formatViewsNumber(9_999_999_999_999)).toBe('10T');
|
||||
// With current rounding rules, this value rounds to whole trillions
|
||||
expect(formatViewsNumber(12_345_678_901_234)).toBe('12T');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fullNumber = true (locale formatting)', () => {
|
||||
test('Returns locale string representation of the full number', () => {
|
||||
// Use a fixed locale independent assertion by stripping non-digits except separators that could vary.
|
||||
// However, to avoid locale variance, check that it equals toLocaleString directly.
|
||||
const vals = [0, 12, 999, 1000, 1234567, 9876543210];
|
||||
for (const v of vals) {
|
||||
expect(formatViewsNumber(v, true)).toBe(v.toLocaleString());
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Additional edge cases and robustness', () => {
|
||||
test('Handles negative values without unit suffix (no scaling applied)', () => {
|
||||
expect(formatViewsNumber(-999)).toBe('-999');
|
||||
expect(formatViewsNumber(-1000)).toBe('-1000');
|
||||
expect(formatViewsNumber(-1500)).toBe('-1500');
|
||||
expect(formatViewsNumber(-10_500)).toBe('-10500');
|
||||
expect(formatViewsNumber(-1_230_000_000_000)).toBe('-1230000000000');
|
||||
});
|
||||
|
||||
test('Handles non-integer inputs with correct rounding in compact mode', () => {
|
||||
expect(formatViewsNumber(1499.5)).toBe('1.5K');
|
||||
expect(formatViewsNumber(999.9)).toBe('1000');
|
||||
expect(formatViewsNumber(10_499.5)).toBe('10K');
|
||||
expect(formatViewsNumber(10_500.49)).toBe('11K');
|
||||
expect(formatViewsNumber(9_440_000.49)).toBe('9.4M');
|
||||
});
|
||||
|
||||
test('Respects locale formatting in fullNumber mode', () => {
|
||||
const values = [1_234_567, -2_345_678, 0, 10_000, 99_999_999];
|
||||
for (const v of values) {
|
||||
expect(formatViewsNumber(v, true)).toBe(v.toLocaleString());
|
||||
}
|
||||
});
|
||||
|
||||
test('Caps unit at trillions for extremely large numbers', () => {
|
||||
expect(formatViewsNumber(9_999_999_999_999)).toBe('10T');
|
||||
expect(formatViewsNumber(12_345_678_901_234)).toBe('12T');
|
||||
expect(formatViewsNumber(987_654_321_000_000)).toBe('988T');
|
||||
});
|
||||
|
||||
// @todo: Revisit this behavior
|
||||
test('Handles NaN and Infinity values gracefully', () => {
|
||||
expect(formatViewsNumber(Number.NaN, true)).toBe(Number.NaN.toLocaleString());
|
||||
expect(formatViewsNumber(Number.POSITIVE_INFINITY, true)).toBe(
|
||||
Number.POSITIVE_INFINITY.toLocaleString()
|
||||
);
|
||||
expect(formatViewsNumber(Number.NEGATIVE_INFINITY, true)).toBe(
|
||||
Number.NEGATIVE_INFINITY.toLocaleString()
|
||||
);
|
||||
|
||||
expect(formatViewsNumber(Number.NaN)).toBe('NaN');
|
||||
|
||||
// @note: We don't test compact Infinity cases due to infinite loop behavior from while (views >= compare)
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
47
frontend/tests/utils/helpers/imageExtension.test.ts
Normal file
47
frontend/tests/utils/helpers/imageExtension.test.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { imageExtension } from '../../../src/static/js/utils/helpers/imageExtension';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('imageExtension', () => {
|
||||
// @todo: 'imageExtension' behaves as a 'fileExtension' function. It should be renamed...
|
||||
test('Returns the extension for a typical filename', () => {
|
||||
expect(imageExtension('photo.png')).toBe('png');
|
||||
expect(imageExtension('document.pdf')).toBe('pdf');
|
||||
});
|
||||
|
||||
test('Returns the last segment for filenames with multiple dots', () => {
|
||||
expect(imageExtension('archive.tar.gz')).toBe('gz');
|
||||
expect(imageExtension('backup.2024.12.31.zip')).toBe('zip');
|
||||
});
|
||||
|
||||
// @todo: It shouldn't happen. Fix that
|
||||
test('Returns the entire string when there is no dot in the filename', () => {
|
||||
expect(imageExtension('file')).toBe('file');
|
||||
expect(imageExtension('README')).toBe('README');
|
||||
});
|
||||
|
||||
test('Handles hidden files that start with a dot', () => {
|
||||
expect(imageExtension('.gitignore')).toBe('gitignore');
|
||||
expect(imageExtension('.env.local')).toBe('local');
|
||||
});
|
||||
|
||||
test('Returns undefined for falsy or empty inputs', () => {
|
||||
expect(imageExtension('')).toBeUndefined();
|
||||
expect(imageExtension(undefined as unknown as string)).toBeUndefined();
|
||||
expect(imageExtension(null as unknown as string)).toBeUndefined();
|
||||
});
|
||||
|
||||
test('Extracts the extension from URL-like paths', () => {
|
||||
expect(imageExtension('https://example.com/images/avatar.jpeg')).toBe('jpeg');
|
||||
expect(imageExtension('/static/assets/icons/favicon.ico')).toBe('ico');
|
||||
});
|
||||
|
||||
test('Preserves case of the extension', () => {
|
||||
expect(imageExtension('UPPER.CASE.JPG')).toBe('JPG');
|
||||
expect(imageExtension('Mixed.Extension.PnG')).toBe('PnG');
|
||||
});
|
||||
|
||||
test('Returns empty string when the filename ends with a trailing dot', () => {
|
||||
expect(imageExtension('weird.')).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
54
frontend/tests/utils/helpers/log.test.ts
Normal file
54
frontend/tests/utils/helpers/log.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { warn, error } from '../../../src/static/js/utils/helpers/log';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('log', () => {
|
||||
beforeEach(() => {
|
||||
// Setup console mocks - replaces global console methods with jest mocks
|
||||
globalThis.console.warn = jest.fn();
|
||||
globalThis.console.error = jest.fn();
|
||||
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original console methods
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('Warn proxies arguments to console.warn preserving order and count', () => {
|
||||
warn('a', 'b', 'c');
|
||||
expect(console.warn).toHaveBeenCalledTimes(1);
|
||||
expect(console.warn).toHaveBeenCalledWith('a', 'b', 'c');
|
||||
});
|
||||
|
||||
test('Error proxies arguments to console.error preserving order and count', () => {
|
||||
error('x', 'y');
|
||||
expect(console.error).toHaveBeenCalledTimes(1);
|
||||
expect(console.error).toHaveBeenCalledWith('x', 'y');
|
||||
});
|
||||
|
||||
test('Warn supports zero arguments', () => {
|
||||
warn();
|
||||
expect(console.warn).toHaveBeenCalledTimes(1);
|
||||
expect((console.warn as jest.Mock).mock.calls[0].length).toBe(0);
|
||||
});
|
||||
|
||||
test('Error supports zero arguments', () => {
|
||||
error();
|
||||
expect(console.error).toHaveBeenCalledTimes(1);
|
||||
expect((console.error as jest.Mock).mock.calls[0].length).toBe(0);
|
||||
});
|
||||
|
||||
test('Warn does not call console.error and error does not call console.warn', () => {
|
||||
warn('only-warn');
|
||||
expect(console.warn).toHaveBeenCalledTimes(1);
|
||||
expect(console.error).not.toHaveBeenCalled();
|
||||
|
||||
jest.clearAllMocks();
|
||||
|
||||
error('only-error');
|
||||
expect(console.error).toHaveBeenCalledTimes(1);
|
||||
expect(console.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
156
frontend/tests/utils/helpers/math.test.ts
Normal file
156
frontend/tests/utils/helpers/math.test.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import {
|
||||
isGt,
|
||||
isZero,
|
||||
isNumber,
|
||||
isInteger,
|
||||
isPositive,
|
||||
isPositiveNumber,
|
||||
isPositiveInteger,
|
||||
isPositiveIntegerOrZero,
|
||||
greaterCommonDivision,
|
||||
} from '../../../src/static/js/utils/helpers/math';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('math', () => {
|
||||
describe('isGt', () => {
|
||||
test('Returns true when x > y', () => {
|
||||
expect(isGt(5, 3)).toBe(true);
|
||||
});
|
||||
|
||||
test('Returns false when x === y', () => {
|
||||
expect(isGt(3, 3)).toBe(false);
|
||||
});
|
||||
|
||||
test('Returns false when x < y', () => {
|
||||
expect(isGt(2, 3)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isZero', () => {
|
||||
test('Returns true for 0', () => {
|
||||
expect(isZero(0)).toBe(true);
|
||||
});
|
||||
|
||||
test('Returns false for non-zero numbers', () => {
|
||||
expect(isZero(1)).toBe(false);
|
||||
expect(isZero(-1)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isNumber', () => {
|
||||
test('Returns true for numbers', () => {
|
||||
expect(isNumber(0)).toBe(true);
|
||||
expect(isNumber(1)).toBe(true);
|
||||
expect(isNumber(-1)).toBe(true);
|
||||
expect(isNumber(1.5)).toBe(true);
|
||||
});
|
||||
|
||||
test('Returns false for NaN', () => {
|
||||
expect(isNumber(Number.NaN as unknown as number)).toBe(false);
|
||||
});
|
||||
|
||||
test('Returns false for non-number types (via casting)', () => {
|
||||
// TypeScript type guards prevent passing non-numbers directly; simulate via casting
|
||||
expect(isNumber('3' as unknown as number)).toBe(false);
|
||||
expect(isNumber(null as unknown as number)).toBe(false);
|
||||
expect(isNumber(undefined as unknown as number)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isInteger', () => {
|
||||
test('Returns true for integers', () => {
|
||||
expect(isInteger(0)).toBe(true);
|
||||
expect(isInteger(1)).toBe(true);
|
||||
expect(isInteger(-1)).toBe(true);
|
||||
});
|
||||
|
||||
test('Returns false for non-integers', () => {
|
||||
expect(isInteger(1.1)).toBe(false);
|
||||
expect(isInteger(-2.5)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isPositive', () => {
|
||||
test('Returns true for positive numbers', () => {
|
||||
expect(isPositive(1)).toBe(true);
|
||||
expect(isPositive(3.14)).toBe(true);
|
||||
});
|
||||
|
||||
test('Returns false for zero and negatives', () => {
|
||||
expect(isPositive(0)).toBe(false);
|
||||
expect(isPositive(-1)).toBe(false);
|
||||
expect(isPositive(-3.14)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isPositiveNumber', () => {
|
||||
test('Returns true for positive numbers', () => {
|
||||
expect(isPositiveNumber(1)).toBe(true);
|
||||
expect(isPositiveNumber(2.7)).toBe(true);
|
||||
});
|
||||
|
||||
test('Returns false for zero and negatives', () => {
|
||||
expect(isPositiveNumber(0)).toBe(false);
|
||||
expect(isPositiveNumber(-1)).toBe(false);
|
||||
expect(isPositiveNumber(-3.4)).toBe(false);
|
||||
});
|
||||
|
||||
test('Returns false for NaN (and non-number when cast)', () => {
|
||||
expect(isPositiveNumber(Number.NaN as unknown as number)).toBe(false);
|
||||
expect(isPositiveNumber('3' as unknown as number)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isPositiveInteger', () => {
|
||||
test('Returns true for positive integers', () => {
|
||||
expect(isPositiveInteger(1)).toBe(true);
|
||||
expect(isPositiveInteger(10)).toBe(true);
|
||||
});
|
||||
|
||||
test('Returns false for zero, negatives, and non-integers', () => {
|
||||
expect(isPositiveInteger(0)).toBe(false);
|
||||
expect(isPositiveInteger(-1)).toBe(false);
|
||||
expect(isPositiveInteger(1.5)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isPositiveIntegerOrZero', () => {
|
||||
test('Returns true for positive integers and zero', () => {
|
||||
expect(isPositiveIntegerOrZero(0)).toBe(true);
|
||||
expect(isPositiveIntegerOrZero(1)).toBe(true);
|
||||
expect(isPositiveIntegerOrZero(10)).toBe(true);
|
||||
});
|
||||
|
||||
test('Returns false for negatives and non-integers', () => {
|
||||
expect(isPositiveIntegerOrZero(-1)).toBe(false);
|
||||
expect(isPositiveIntegerOrZero(1.1)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('greaterCommonDivision', () => {
|
||||
test('Computes gcd for positive integers', () => {
|
||||
expect(greaterCommonDivision(54, 24)).toBe(6);
|
||||
expect(greaterCommonDivision(24, 54)).toBe(6);
|
||||
expect(greaterCommonDivision(21, 14)).toBe(7);
|
||||
expect(greaterCommonDivision(7, 13)).toBe(1);
|
||||
});
|
||||
|
||||
test('Handles zeros', () => {
|
||||
expect(greaterCommonDivision(0, 0)).toBe(0);
|
||||
expect(greaterCommonDivision(0, 5)).toBe(5);
|
||||
expect(greaterCommonDivision(12, 0)).toBe(12);
|
||||
});
|
||||
|
||||
test('Handles negative numbers by returning gcd sign of first arg (Euclid recursion behavior)', () => {
|
||||
expect(greaterCommonDivision(-54, 24)).toBe(-6);
|
||||
expect(greaterCommonDivision(54, -24)).toBe(6);
|
||||
expect(greaterCommonDivision(-54, -24)).toBe(-6);
|
||||
});
|
||||
|
||||
test('Works with equal numbers', () => {
|
||||
expect(greaterCommonDivision(8, 8)).toBe(8);
|
||||
expect(greaterCommonDivision(-8, -8)).toBe(-8);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
111
frontend/tests/utils/helpers/propTypeFilters.test.ts
Normal file
111
frontend/tests/utils/helpers/propTypeFilters.test.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
// Mock the errors helper to capture error construction without side effects
|
||||
jest.mock('../../../src/static/js/utils/helpers/errors', () => ({
|
||||
logErrorAndReturnError: jest.fn((messages: string[]) => new Error(messages.join('\n'))),
|
||||
}));
|
||||
|
||||
import { logErrorAndReturnError } from '../../../src/static/js/utils/helpers/errors';
|
||||
import { PositiveIntegerOrZero, PositiveInteger } from '../../../src/static/js/utils/helpers/propTypeFilters';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('propTypeFilters', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('PositiveIntegerOrZero', () => {
|
||||
test('Returns null when property is undefined', () => {
|
||||
const obj = {};
|
||||
const res = PositiveIntegerOrZero(obj, 'count', 'Comp');
|
||||
expect(res).toBeNull();
|
||||
expect(logErrorAndReturnError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('Returns null for zero or positive integers', () => {
|
||||
const cases = [0, 1, 2, 100];
|
||||
for (const val of cases) {
|
||||
const res = PositiveIntegerOrZero({ count: val }, 'count', 'Comp');
|
||||
expect(res).toBeNull();
|
||||
}
|
||||
expect(logErrorAndReturnError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('Returns Error via logErrorAndReturnError for negative numbers', () => {
|
||||
const res = PositiveIntegerOrZero({ count: -1 }, 'count', 'Counter');
|
||||
expect(res).toBeInstanceOf(Error);
|
||||
expect(logErrorAndReturnError).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [messages] = (logErrorAndReturnError as jest.Mock).mock.calls[0];
|
||||
expect(Array.isArray(messages)).toBe(true);
|
||||
expect(messages[0]).toBe(
|
||||
'Invalid prop `count` of type `number` supplied to `Counter`, expected `positive integer or zero` (-1).'
|
||||
);
|
||||
});
|
||||
|
||||
test('Returns Error for non-integer numbers (e.g., float)', () => {
|
||||
const res = PositiveIntegerOrZero({ count: 1.5 }, 'count', 'Widget');
|
||||
expect(res).toBeInstanceOf(Error);
|
||||
expect((logErrorAndReturnError as jest.Mock).mock.calls[0][0][0]).toBe(
|
||||
'Invalid prop `count` of type `number` supplied to `Widget`, expected `positive integer or zero` (1.5).'
|
||||
);
|
||||
});
|
||||
|
||||
test('Uses "N/A" component label when comp is falsy', () => {
|
||||
const res = PositiveIntegerOrZero({ count: -2 }, 'count', '');
|
||||
expect(res).toBeInstanceOf(Error);
|
||||
expect((logErrorAndReturnError as jest.Mock).mock.calls[0][0][0]).toBe(
|
||||
'Invalid prop `count` of type `number` supplied to `N/A`, expected `positive integer or zero` (-2).'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PositiveInteger', () => {
|
||||
test('Returns null when property is undefined', () => {
|
||||
const obj = {};
|
||||
const res = PositiveInteger(obj, 'age', 'Person');
|
||||
expect(res).toBeNull();
|
||||
expect(logErrorAndReturnError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('Returns null for positive integers (excluding zero)', () => {
|
||||
const cases = [1, 2, 100];
|
||||
for (const val of cases) {
|
||||
const res = PositiveInteger({ age: val }, 'age', 'Person');
|
||||
expect(res).toBeNull();
|
||||
}
|
||||
expect(logErrorAndReturnError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('Returns Error for zero', () => {
|
||||
const res = PositiveInteger({ age: 0 }, 'age', 'Person');
|
||||
expect(res).toBeInstanceOf(Error);
|
||||
expect((logErrorAndReturnError as jest.Mock).mock.calls[0][0][0]).toContain(
|
||||
'Invalid prop `age` of type `number` supplied to `Person`, expected `positive integer` (0).'
|
||||
);
|
||||
});
|
||||
|
||||
test('Returns Error for negative numbers', () => {
|
||||
const res = PositiveInteger({ age: -3 }, 'age', 'Person');
|
||||
expect(res).toBeInstanceOf(Error);
|
||||
expect((logErrorAndReturnError as jest.Mock).mock.calls[0][0][0]).toBe(
|
||||
'Invalid prop `age` of type `number` supplied to `Person`, expected `positive integer` (-3).'
|
||||
);
|
||||
});
|
||||
|
||||
test('Returns Error for non-integer numbers', () => {
|
||||
const res = PositiveInteger({ age: 2.7 }, 'age', 'Person');
|
||||
expect(res).toBeInstanceOf(Error);
|
||||
expect((logErrorAndReturnError as jest.Mock).mock.calls[0][0][0]).toBe(
|
||||
'Invalid prop `age` of type `number` supplied to `Person`, expected `positive integer` (2.7).'
|
||||
);
|
||||
});
|
||||
|
||||
test('Uses "N/A" component label when comp is falsy', () => {
|
||||
const res = PositiveInteger({ age: -1 }, 'age', '');
|
||||
expect(res).toBeInstanceOf(Error);
|
||||
expect((logErrorAndReturnError as jest.Mock).mock.calls[0][0][0]).toBe(
|
||||
'Invalid prop `age` of type `number` supplied to `N/A`, expected `positive integer` (-1).'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
33
frontend/tests/utils/helpers/publishedOnDate.test.ts
Normal file
33
frontend/tests/utils/helpers/publishedOnDate.test.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import publishedOnDate from '../../../src/static/js/utils/helpers/publishedOnDate';
|
||||
|
||||
// Helper to create Date in UTC to avoid timezone issues in CI environments
|
||||
const makeDate = (y: number, mZeroBased: number, d: number) => new Date(Date.UTC(y, mZeroBased, d));
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('publishedOnDate', () => {
|
||||
test('Returns null when input is not a Date instance', () => {
|
||||
expect(publishedOnDate(null as unknown as Date)).toBeNull();
|
||||
expect(publishedOnDate(undefined as unknown as Date)).toBeNull();
|
||||
expect(publishedOnDate('2020-01-02' as any as Date)).toBeNull();
|
||||
expect(publishedOnDate(1577923200000 as unknown as Date)).toBeNull();
|
||||
});
|
||||
|
||||
test('Type 1 (default): "Mon DD, YYYY" with 3-letter month prefix before day', () => {
|
||||
expect(publishedOnDate(makeDate(2020, 0, 2))).toBe('Jan 2, 2020');
|
||||
expect(publishedOnDate(makeDate(1999, 11, 31))).toBe('Dec 31, 1999');
|
||||
expect(publishedOnDate(makeDate(2024, 1, 29))).toBe('Feb 29, 2024');
|
||||
});
|
||||
|
||||
test('Type 2: "DD Mon YYYY" with 3-letter month suffix', () => {
|
||||
expect(publishedOnDate(makeDate(2020, 0, 2), 2)).toBe('2 Jan 2020');
|
||||
expect(publishedOnDate(makeDate(1999, 11, 31), 2)).toBe('31 Dec 1999');
|
||||
expect(publishedOnDate(makeDate(2024, 1, 29), 2)).toBe('29 Feb 2024');
|
||||
});
|
||||
|
||||
test('Type 3: "DD Month YYYY" with full month name', () => {
|
||||
expect(publishedOnDate(makeDate(2020, 0, 2), 3)).toBe('2 January 2020');
|
||||
expect(publishedOnDate(makeDate(1999, 11, 31), 3)).toBe('31 December 1999');
|
||||
expect(publishedOnDate(makeDate(2024, 1, 29), 3)).toBe('29 February 2024');
|
||||
});
|
||||
});
|
||||
});
|
||||
45
frontend/tests/utils/helpers/quickSort.test.ts
Normal file
45
frontend/tests/utils/helpers/quickSort.test.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { quickSort } from '../../../src/static/js/utils/helpers/quickSort';
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('quickSort', () => {
|
||||
test('Returns the same array reference (in-place) and sorts ascending', () => {
|
||||
const arr = [3, 1, 4, 1, 5, 9, 2];
|
||||
const out = quickSort(arr, 0, arr.length - 1);
|
||||
expect(out).toBe(arr);
|
||||
expect(arr).toEqual([1, 1, 2, 3, 4, 5, 9]);
|
||||
});
|
||||
|
||||
test('Handles already sorted arrays', () => {
|
||||
const arr = [1, 2, 3, 4, 5];
|
||||
quickSort(arr, 0, arr.length - 1);
|
||||
expect(arr).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
test('Handles arrays with duplicates and negative numbers', () => {
|
||||
const arr = [0, -1, -1, 2, 2, 1, 0];
|
||||
quickSort(arr, 0, arr.length - 1);
|
||||
expect(arr).toEqual([-1, -1, 0, 0, 1, 2, 2]);
|
||||
});
|
||||
|
||||
test('Handles single-element array', () => {
|
||||
const single = [42];
|
||||
quickSort(single, 0, single.length - 1);
|
||||
expect(single).toEqual([42]);
|
||||
});
|
||||
|
||||
test('Handles empty range without changes', () => {
|
||||
const arr = [5, 4, 3];
|
||||
// call with left > right (empty range)
|
||||
quickSort(arr, 2, 1);
|
||||
expect(arr).toEqual([5, 4, 3]);
|
||||
});
|
||||
|
||||
test('Sorts subrange correctly without touching elements outside range', () => {
|
||||
const arr = [9, 7, 5, 3, 1, 2, 4, 8, 6];
|
||||
// sort only the middle [2..6]
|
||||
quickSort(arr, 2, 6);
|
||||
// The subrange [5,3,1,2,4] becomes [1,2,3,4,5]
|
||||
expect(arr).toEqual([9, 7, 1, 2, 3, 4, 5, 8, 6]);
|
||||
});
|
||||
});
|
||||
});
|
||||
68
frontend/tests/utils/helpers/replacementStrings.test.ts
Normal file
68
frontend/tests/utils/helpers/replacementStrings.test.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { replaceString } from '../../../src/static/js/utils/helpers/replacementStrings';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
REPLACEMENTS?: Record<string, string>;
|
||||
}
|
||||
}
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('replacementStrings', () => {
|
||||
describe('replaceString', () => {
|
||||
const originalReplacements = window.REPLACEMENTS;
|
||||
|
||||
beforeEach(() => {
|
||||
delete window.REPLACEMENTS;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.REPLACEMENTS = originalReplacements;
|
||||
});
|
||||
|
||||
test('Returns the original word when window.REPLACEMENTS is undefined', () => {
|
||||
delete window.REPLACEMENTS;
|
||||
const input = 'Hello World';
|
||||
const output = replaceString(input);
|
||||
expect(output).toBe(input);
|
||||
});
|
||||
|
||||
test('Replaces a single occurrence based on window.REPLACEMENTS map', () => {
|
||||
window.REPLACEMENTS = { Hello: 'Hi' };
|
||||
const output = replaceString('Hello World');
|
||||
expect(output).toBe('Hi World');
|
||||
});
|
||||
|
||||
test('Replaces multiple occurrences of the same key', () => {
|
||||
window.REPLACEMENTS = { foo: 'bar' };
|
||||
const output = replaceString('foo foo baz foo');
|
||||
expect(output).toBe('bar bar baz bar');
|
||||
});
|
||||
|
||||
test('Applies all entries in window.REPLACEMENTS (sequential split/join)', () => {
|
||||
window.REPLACEMENTS = { a: 'A', A: 'X' };
|
||||
// First replaces 'a'->'A' and then 'A'->'X'
|
||||
const output = replaceString('aAaa');
|
||||
expect(output).toBe('XXXX');
|
||||
});
|
||||
|
||||
test('Supports empty string replacements (deletion)', () => {
|
||||
window.REPLACEMENTS = { remove: '' };
|
||||
const output = replaceString('please remove this');
|
||||
expect(output).toBe('please this');
|
||||
});
|
||||
|
||||
test('Handles overlapping keys by iteration order', () => {
|
||||
window.REPLACEMENTS = { ab: 'X', b: 'Y' };
|
||||
// First replaces 'ab' -> 'X', leaving no 'b' from that sequence, then replace standalone 'b' -> 'Y'
|
||||
const output = replaceString('zab+b');
|
||||
expect(output).toBe('zX+Y');
|
||||
});
|
||||
|
||||
test('Works with special regex characters since split/join is literal', () => {
|
||||
window.REPLACEMENTS = { '.': 'DOT', '*': 'STAR', '[]': 'BRACKETS' };
|
||||
const output = replaceString('a.*b[]c.');
|
||||
expect(output).toBe('aDOTSTARbBRACKETScDOT');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
218
frontend/tests/utils/helpers/requests.test.ts
Normal file
218
frontend/tests/utils/helpers/requests.test.ts
Normal file
@@ -0,0 +1,218 @@
|
||||
import axios from 'axios';
|
||||
import { getRequest, postRequest, putRequest, deleteRequest } from '../../../src/static/js/utils/helpers/requests';
|
||||
|
||||
jest.mock('axios');
|
||||
|
||||
const mockedAxios = axios as jest.Mocked<typeof axios>;
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('requests', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('getRequest', () => {
|
||||
const url = '/api/test';
|
||||
|
||||
test('Calls axios.get with url and default config (async mode)', () => {
|
||||
mockedAxios.get.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
const cb = jest.fn();
|
||||
|
||||
getRequest(url, false, cb, undefined);
|
||||
|
||||
expect(mockedAxios.get).toHaveBeenCalledWith(url, {
|
||||
timeout: null,
|
||||
maxContentLength: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('Invokes callback when provided (async mode)', async () => {
|
||||
const response = { data: 'ok' } as any;
|
||||
mockedAxios.get.mockResolvedValueOnce(response);
|
||||
const cb = jest.fn();
|
||||
|
||||
await getRequest(url, true, cb, undefined);
|
||||
|
||||
expect(cb).toHaveBeenCalledWith(response);
|
||||
});
|
||||
|
||||
// @todo: Revisit this behavior
|
||||
test('Does not throw when callback is not a function', async () => {
|
||||
mockedAxios.get.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
await expect(getRequest(url, true, undefined as any, undefined as any)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('Error handler wraps network errors with type network', async () => {
|
||||
const networkError = new Error('Network Error');
|
||||
mockedAxios.get.mockRejectedValueOnce(networkError);
|
||||
const errorCb = jest.fn();
|
||||
|
||||
await getRequest(url, true, undefined, errorCb);
|
||||
|
||||
expect(errorCb).toHaveBeenCalledTimes(1);
|
||||
const arg = errorCb.mock.calls[0][0];
|
||||
expect(arg).toStrictEqual({ type: 'network', error: networkError });
|
||||
});
|
||||
|
||||
test('Error handler maps status 401 to private error', async () => {
|
||||
const error = { response: { status: 401 } };
|
||||
mockedAxios.get.mockRejectedValueOnce(error);
|
||||
const errorCb = jest.fn();
|
||||
|
||||
await getRequest(url, true, undefined, errorCb);
|
||||
|
||||
expect(errorCb).toHaveBeenCalledWith({
|
||||
type: 'private',
|
||||
error,
|
||||
message: 'Media is private',
|
||||
});
|
||||
});
|
||||
|
||||
test('Error handler maps status 400 to unavailable error', async () => {
|
||||
const error = { response: { status: 400 } };
|
||||
mockedAxios.get.mockRejectedValueOnce(error);
|
||||
const errorCb = jest.fn();
|
||||
|
||||
await getRequest(url, true, undefined, errorCb);
|
||||
|
||||
expect(errorCb).toHaveBeenCalledWith({
|
||||
type: 'unavailable',
|
||||
error,
|
||||
message: 'Media is unavailable',
|
||||
});
|
||||
});
|
||||
|
||||
test('Passes through other errors with error.response defined but no status', async () => {
|
||||
const error = { response: {} } as any;
|
||||
mockedAxios.get.mockRejectedValueOnce(error);
|
||||
const errorCb = jest.fn();
|
||||
|
||||
await getRequest(url, true, undefined, errorCb);
|
||||
|
||||
expect(errorCb).toHaveBeenCalledWith(error);
|
||||
});
|
||||
|
||||
// @todo: Revisit this behavior
|
||||
test('When no errorCallback provided, it should not crash on error (async)', async () => {
|
||||
mockedAxios.get.mockRejectedValueOnce(new Error('boom'));
|
||||
await expect(getRequest(url, true, undefined as any, undefined as any)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('postRequest', () => {
|
||||
const url = '/api/post';
|
||||
|
||||
test('Calls axios.post with provided data and config (async mode)', () => {
|
||||
mockedAxios.post.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
const cb = jest.fn();
|
||||
|
||||
postRequest(url, { a: 1 }, { headers: { h: 'v' } }, false, cb, undefined);
|
||||
|
||||
expect(mockedAxios.post).toHaveBeenCalledWith(url, { a: 1 }, { headers: { h: 'v' } });
|
||||
});
|
||||
|
||||
test('Defaults postData to {} when undefined', async () => {
|
||||
mockedAxios.post.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
const cb = jest.fn();
|
||||
|
||||
await postRequest(url, undefined as any, undefined as any, true, cb, undefined);
|
||||
|
||||
expect(mockedAxios.post).toHaveBeenCalledWith(url, {}, null);
|
||||
expect(cb).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('Invokes errorCallback on error as-is', async () => {
|
||||
const error = new Error('fail');
|
||||
mockedAxios.post.mockRejectedValueOnce(error);
|
||||
const errorCb = jest.fn();
|
||||
|
||||
await postRequest(url, {}, undefined, true, undefined, errorCb);
|
||||
|
||||
expect(errorCb).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
||||
describe('putRequest', () => {
|
||||
const url = '/api/put';
|
||||
|
||||
test('Calls axios.put with provided data and config', async () => {
|
||||
mockedAxios.put.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
const cb = jest.fn();
|
||||
|
||||
await putRequest(url, { a: 1 }, { headers: { h: 'v' } }, true, cb, undefined);
|
||||
|
||||
expect(mockedAxios.put).toHaveBeenCalledWith(url, { a: 1 }, { headers: { h: 'v' } });
|
||||
expect(cb).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('Defaults putData to {} when undefined', async () => {
|
||||
mockedAxios.put.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
|
||||
await putRequest(url, undefined as any, undefined as any, true, undefined, undefined);
|
||||
|
||||
expect(mockedAxios.put).toHaveBeenCalledWith(url, {}, null);
|
||||
});
|
||||
|
||||
test('Invokes errorCallback on error', async () => {
|
||||
const error = new Error('fail');
|
||||
mockedAxios.put.mockRejectedValueOnce(error);
|
||||
const errorCb = jest.fn();
|
||||
|
||||
await putRequest(url, {}, undefined, true, undefined, errorCb);
|
||||
|
||||
expect(errorCb).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteRequest', () => {
|
||||
const url = '/api/delete';
|
||||
|
||||
test('Calls axios.delete with provided config', async () => {
|
||||
mockedAxios.delete.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
const cb = jest.fn();
|
||||
|
||||
await deleteRequest(url, { headers: { h: 'v' } }, true, cb, undefined);
|
||||
|
||||
expect(mockedAxios.delete).toHaveBeenCalledWith(url, { headers: { h: 'v' } });
|
||||
expect(cb).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('Defaults configData to {} when undefined', async () => {
|
||||
mockedAxios.delete.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
|
||||
await deleteRequest(url, undefined as any, true, undefined, undefined);
|
||||
|
||||
expect(mockedAxios.delete).toHaveBeenCalledWith(url, {});
|
||||
});
|
||||
|
||||
test('Invokes errorCallback on error', async () => {
|
||||
const error = new Error('fail');
|
||||
mockedAxios.delete.mockRejectedValueOnce(error);
|
||||
const errorCb = jest.fn();
|
||||
|
||||
await deleteRequest(url, {}, true, undefined, errorCb);
|
||||
|
||||
expect(errorCb).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sync vs async behavior', () => {
|
||||
test('sync=true awaits the axios promise', async () => {
|
||||
const thenable = Promise.resolve({ data: 'ok' } as any);
|
||||
mockedAxios.post.mockReturnValueOnce(thenable as any);
|
||||
const cb = jest.fn();
|
||||
|
||||
const p = postRequest('/api/p', {}, undefined, true, cb, undefined);
|
||||
// When awaited, callback should be called before next tick
|
||||
await p;
|
||||
expect(cb).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('sync=false does not need awaiting; call still issued', () => {
|
||||
mockedAxios.put.mockResolvedValueOnce({ data: 'ok' } as any);
|
||||
putRequest('/api/p', {}, undefined, false, undefined, undefined);
|
||||
expect(mockedAxios.put).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
53
frontend/tests/utils/helpers/translate.test.ts
Normal file
53
frontend/tests/utils/helpers/translate.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { translateString } from '../../../src/static/js/utils/helpers/translate';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
TRANSLATION?: Record<string, string>;
|
||||
}
|
||||
}
|
||||
|
||||
describe('js/utils/helpers', () => {
|
||||
describe('translate', () => {
|
||||
const originalReplacements = window.TRANSLATION;
|
||||
|
||||
beforeEach(() => {
|
||||
delete window.TRANSLATION;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.TRANSLATION = originalReplacements;
|
||||
});
|
||||
|
||||
test('Returns the same word when window.TRANSLATION is undefined', () => {
|
||||
delete window.TRANSLATION;
|
||||
expect(translateString('Hello')).toBe('Hello');
|
||||
expect(translateString('NonExistingKey')).toBe('NonExistingKey');
|
||||
expect(translateString('')).toBe('');
|
||||
});
|
||||
|
||||
test('Returns mapped value when key exists in window.TRANSLATION', () => {
|
||||
window.TRANSLATION = { Hello: 'Γεια', World: 'Κόσμος' };
|
||||
expect(translateString('Hello')).toBe('Γεια');
|
||||
expect(translateString('World')).toBe('Κόσμος');
|
||||
});
|
||||
|
||||
test('Falls back to original word when key is missing in Twindow.RANSLATION', () => {
|
||||
window.TRANSLATION = { Hello: 'Γεια' };
|
||||
expect(translateString('MissingKey')).toBe('MissingKey');
|
||||
expect(translateString('AnotherMissing')).toBe('AnotherMissing');
|
||||
});
|
||||
|
||||
test('Supports empty string keys distinctly from missing keys', () => {
|
||||
window.TRANSLATION = { '': '(empty)' };
|
||||
expect(translateString('')).toBe('(empty)');
|
||||
expect(translateString(' ')).toBe(' ');
|
||||
});
|
||||
|
||||
test('Returns value as-is even if it is an empty string or falsy in the dictionary', () => {
|
||||
window.TRANSLATION = { Empty: '', Zero: '0', False: 'false' };
|
||||
expect(translateString('Empty')).toBe('');
|
||||
expect(translateString('Zero')).toBe('0');
|
||||
expect(translateString('False')).toBe('false');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user