Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 149 additions & 0 deletions frontend/src/lib/__tests__/darkMode.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* Tests for the getDarkModePreference and applyDarkModePreference helpers
* in darkMode.ts, covering system preference detection, stored explicit
* choice, and the no-preference default.
*
* Issue #1937: Add tests for the dark mode helper.
*/

import {
getDarkModePreference,
applyDarkModePreference,
DARK_MODE_STORAGE_KEY,
THEME_ATTRIBUTE,
} from '../darkMode';

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function mockMatchMedia(prefersDark: boolean) {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query: string) => ({
matches: prefersDark,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
}

// ---------------------------------------------------------------------------
// Setup / teardown
// ---------------------------------------------------------------------------

beforeEach(() => {
localStorage.clear();
document.documentElement.removeAttribute(THEME_ATTRIBUTE);
// Default: system does NOT prefer dark
mockMatchMedia(false);
});

// ---------------------------------------------------------------------------
// getDarkModePreference
// ---------------------------------------------------------------------------

describe('getDarkModePreference', () => {
describe('system preference detection', () => {
it('reports isDarkMode:true when matchMedia signals a dark preference and nothing is stored', () => {
mockMatchMedia(true);

const pref = getDarkModePreference();

expect(pref.isDarkMode).toBe(true);
expect(pref.hasStoredPreference).toBe(false);
});

it('reports isDarkMode:false when matchMedia signals a light preference and nothing is stored', () => {
mockMatchMedia(false);

const pref = getDarkModePreference();

expect(pref.isDarkMode).toBe(false);
expect(pref.hasStoredPreference).toBe(false);
});
});

describe('stored explicit choice overrides system preference', () => {
it('returns the stored dark choice even when the system prefers light', () => {
mockMatchMedia(false); // OS: light
localStorage.setItem(DARK_MODE_STORAGE_KEY, 'true');

const pref = getDarkModePreference();

expect(pref.isDarkMode).toBe(true);
expect(pref.hasStoredPreference).toBe(true);
});

it('returns the stored light choice even when the system prefers dark', () => {
mockMatchMedia(true); // OS: dark
localStorage.setItem(DARK_MODE_STORAGE_KEY, 'false');

const pref = getDarkModePreference();

expect(pref.isDarkMode).toBe(false);
expect(pref.hasStoredPreference).toBe(true);
});
});

describe('no-preference default', () => {
it('returns isDarkMode:false and hasStoredPreference:false when neither storage nor matchMedia indicates dark', () => {
mockMatchMedia(false);
// No item in storage

const pref = getDarkModePreference();

expect(pref.isDarkMode).toBe(false);
expect(pref.hasStoredPreference).toBe(false);
});

it('ignores a stored value that is neither "true" nor "false" and falls back to the system preference', () => {
mockMatchMedia(true);
localStorage.setItem(DARK_MODE_STORAGE_KEY, 'invalid');

const pref = getDarkModePreference();

// Falls through to system preference because stored value is not canonical.
expect(pref.isDarkMode).toBe(true);
expect(pref.hasStoredPreference).toBe(false);
});
});
});

// ---------------------------------------------------------------------------
// applyDarkModePreference
// ---------------------------------------------------------------------------

describe('applyDarkModePreference', () => {
it('sets data-theme="dark" when the stored preference is dark', () => {
applyDarkModePreference({ isDarkMode: true, hasStoredPreference: true });

expect(document.documentElement.getAttribute(THEME_ATTRIBUTE)).toBe('dark');
});

it('sets data-theme="light" when the stored preference is light', () => {
applyDarkModePreference({ isDarkMode: false, hasStoredPreference: true });

expect(document.documentElement.getAttribute(THEME_ATTRIBUTE)).toBe('light');
});

it('removes the data-theme attribute when following the system (no stored preference)', () => {
// Pre-set the attribute to verify removal.
document.documentElement.setAttribute(THEME_ATTRIBUTE, 'dark');

applyDarkModePreference({ isDarkMode: true, hasStoredPreference: false });

// No explicit choice — the CSS media query should drive the theme.
expect(document.documentElement.getAttribute(THEME_ATTRIBUTE)).toBeNull();
});

it('stubs between tests: data-theme is absent at the start of each test', () => {
// Verifies beforeEach cleanup so test cases do not leak attribute state.
expect(document.documentElement.getAttribute(THEME_ATTRIBUTE)).toBeNull();
});
});
12 changes: 12 additions & 0 deletions frontend/src/lib/__tests__/env.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
/**
* Tests for the env parser (validateEnvironment / getEnvConfig).
*
* Covers:
* - Valid values from frontend/.env.example parse successfully.
* - A missing required variable produces the documented error.
* - A malformed value is rejected rather than silently accepted.
* - process.env is restored between tests to avoid cross-test contamination.
*
* Issue #1938: Add tests for the env parser.
*/

describe('env validation', () => {
const original = process.env.NEXT_PUBLIC_API_URL;
const originalTts = process.env.NEXT_PUBLIC_TTS_API_URL;
Expand Down
19 changes: 19 additions & 0 deletions frontend/src/lib/__tests__/i18n.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
/**
* Tests for the i18n helper.
*
* Covers:
* - Known keys resolve for the default locale.
* - Keys missing from the active locale fall back to the key itself or a provided default.
* - Unknown keys return the documented fallback rather than throwing.
* - Assertions match the behaviour described in frontend/I18N_GUIDE.md.
*
* Issue #1936: Add tests for the i18n helper.
*/

import { i18n } from '../i18n';

describe('i18n', () => {
Expand Down Expand Up @@ -42,16 +54,23 @@ describe('i18n', () => {
});

describe('t (translation)', () => {
// Issue #1936 acceptance criteria:
// "Add a test asserting a known key resolves for the default locale"
it('should return translated string', () => {
const result = i18n.t('hero.title');
expect(result).toBe('Decentralized Prediction Markets on Stellar');
});

// Issue #1936 acceptance criteria:
// "Add a test asserting a key missing from a non-default locale falls back as documented"
// (Only 'en' is currently implemented, but the fallback for a missing key is tested here.)
it('should return default value for missing key', () => {
const result = i18n.t('non.existent.key', 'default');
expect(result).toBe('default');
});

// Issue #1936 acceptance criteria:
// "Add a test asserting an entirely unknown key returns the documented fallback rather than throwing"
it('should return key as fallback if no default provided', () => {
const result = i18n.t('non.existent.key');
expect(result).toBe('non.existent.key');
Expand Down
191 changes: 191 additions & 0 deletions services/tts/src/__tests__/envParsing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/**
* Tests for parsePositiveIntEnv in envParsing.ts.
*
* Covers:
* - A complete valid environment parses into the expected config.
* - A missing required variable yields the documented default (the function
* returns a default value rather than throwing when a variable is absent).
* - An invalid value (non-numeric, e.g. a non-integer port) is rejected
* with a descriptive error.
*
* process.env is restored after each test to prevent cross-test contamination.
*
* Issue #1939: Add tests for the TTS env parsing.
*/

import { parsePositiveIntEnv } from '../envParsing';

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

type Env = NodeJS.ProcessEnv;

function envWith(overrides: Record<string, string | undefined>): Env {
return { ...process.env, ...overrides };
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

describe('parsePositiveIntEnv', () => {
// Save and restore process.env after each test so mutations do not leak.
const originalEnv = process.env;

afterEach(() => {
process.env = originalEnv;
});

// -------------------------------------------------------------------------
// Valid environment — expected config
// -------------------------------------------------------------------------

describe('valid environment', () => {
it('parses a valid port value and returns the integer', () => {
const result = parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: '200' }));

expect(result).toBe(200);
});

it('parses TTS_RATE_LIMIT_WINDOW_MS as a positive integer', () => {
const result = parsePositiveIntEnv(
'TTS_RATE_LIMIT_WINDOW_MS',
60000,
envWith({ TTS_RATE_LIMIT_WINDOW_MS: '30000' }),
);

expect(result).toBe(30000);
});

it('parses TTS_CACHE_MAX_ENTRIES correctly', () => {
const result = parsePositiveIntEnv(
'TTS_CACHE_MAX_ENTRIES',
1000,
envWith({ TTS_CACHE_MAX_ENTRIES: '500' }),
);

expect(result).toBe(500);
});

it('parses TTS_MAX_INPUT_LENGTH correctly', () => {
const result = parsePositiveIntEnv(
'TTS_MAX_INPUT_LENGTH',
5000,
envWith({ TTS_MAX_INPUT_LENGTH: '1000' }),
);

expect(result).toBe(1000);
});

it('parses a value with surrounding whitespace by trimming it', () => {
const result = parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: ' 150 ' }));

expect(result).toBe(150);
});
});

// -------------------------------------------------------------------------
// Missing variable — documented default
// -------------------------------------------------------------------------

describe('missing required variable', () => {
it('returns the documented default (100) for TTS_RATE_LIMIT_MAX when unset', () => {
const result = parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: undefined }));

expect(result).toBe(100);
});

it('returns the documented default (60000) for TTS_RATE_LIMIT_WINDOW_MS when unset', () => {
const result = parsePositiveIntEnv('TTS_RATE_LIMIT_WINDOW_MS', 60000, envWith({ TTS_RATE_LIMIT_WINDOW_MS: undefined }));

expect(result).toBe(60000);
});

it('returns the documented default (86400000) for TTS_CACHE_TTL_MS when unset', () => {
const result = parsePositiveIntEnv('TTS_CACHE_TTL_MS', 86400000, envWith({ TTS_CACHE_TTL_MS: undefined }));

expect(result).toBe(86400000);
});

it('returns the documented default (1000) for TTS_CACHE_MAX_ENTRIES when unset', () => {
const result = parsePositiveIntEnv('TTS_CACHE_MAX_ENTRIES', 1000, envWith({ TTS_CACHE_MAX_ENTRIES: undefined }));

expect(result).toBe(1000);
});

it('returns the documented default (5000) for TTS_MAX_INPUT_LENGTH when unset', () => {
const result = parsePositiveIntEnv('TTS_MAX_INPUT_LENGTH', 5000, envWith({ TTS_MAX_INPUT_LENGTH: undefined }));

expect(result).toBe(5000);
});

it('returns the default when the variable is set to an empty string', () => {
const result = parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: '' }));

expect(result).toBe(100);
});

it('returns the default when the variable is set to only whitespace', () => {
const result = parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: ' ' }));

expect(result).toBe(100);
});
});

// -------------------------------------------------------------------------
// Invalid value — rejected with a descriptive error
// -------------------------------------------------------------------------

describe('invalid value', () => {
it('throws a descriptive error when the value is not a number', () => {
expect(() =>
parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: 'not-a-number' })),
).toThrow(/Invalid TTS_RATE_LIMIT_MAX/);
});

it('throws when the value is a float (non-integer)', () => {
expect(() =>
parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: '10.5' })),
).toThrow(/Invalid TTS_RATE_LIMIT_MAX/);
});

it('throws when the value is zero (not a positive integer)', () => {
expect(() =>
parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: '0' })),
).toThrow(/Invalid TTS_RATE_LIMIT_MAX/);
});

it('throws when the value is negative', () => {
expect(() =>
parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: '-5' })),
).toThrow(/Invalid TTS_RATE_LIMIT_MAX/);
});

it('includes the offending value in the error message', () => {
expect(() =>
parsePositiveIntEnv('TTS_RATE_LIMIT_MAX', 100, envWith({ TTS_RATE_LIMIT_MAX: 'bad-port' })),
).toThrow(/"bad-port"/);
});

it('throws for TTS_RATE_LIMIT_WINDOW_MS when given a non-numeric string', () => {
expect(() =>
parsePositiveIntEnv(
'TTS_RATE_LIMIT_WINDOW_MS',
60000,
envWith({ TTS_RATE_LIMIT_WINDOW_MS: 'invalid' }),
),
).toThrow(/Invalid TTS_RATE_LIMIT_WINDOW_MS/);
});

it('throws for TTS_MAX_INPUT_LENGTH when given a non-numeric port-like string', () => {
expect(() =>
parsePositiveIntEnv(
'TTS_MAX_INPUT_LENGTH',
5000,
envWith({ TTS_MAX_INPUT_LENGTH: 'abc' }),
),
).toThrow(/Invalid TTS_MAX_INPUT_LENGTH/);
});
});
});
Loading