Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(app): remove i18n, user settings and premium helper tests

Hampusbdc3d83a16ad
diff --git a/fluxer_app/src/features/i18n/components/AppI18nProvider.test.tsx b/fluxer_app/src/features/i18n/components/AppI18nProvider.test.tsx
deleted file mode 100644
index 069f784fe..000000000
--- a/fluxer_app/src/features/i18n/components/AppI18nProvider.test.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {AppI18nProvider} from '@app/features/i18n/components/AppI18nProvider';
-import {commitUnderTranslation} from '@app/features/i18n/testing/TranslationCommitHarness';
-import {
- findTranslationUnsafeTextNodes,
- TRANSLATION_MARKER,
- TRANSLATOR_PIPELINE_NAMES,
- TranslatorPipelines,
-} from '@app/features/i18n/testing/TranslatorSimulation';
-import {i18n} from '@lingui/core';
-import {I18nProvider, Trans} from '@lingui/react';
-import {createElement, type ReactNode} from 'react';
-import {afterEach, beforeAll, describe, expect, it} from 'vitest';
-
-const ENGLISH = {
- simple: 'Monthly {price}',
- rich: 'Renews on <0>{date}</0>. Enjoy!',
- nested: 'Renews on <0>{date} at <1>noon</1></0>. Enjoy!',
-};
-const GERMAN = {
- simple: 'Monatlich {price}',
- rich: '<0>{date}</0> ist das Datum. Viel Spass!',
- nested: 'Ende <0><1>mittags</1> am {date}</0>. Viel Spass!',
-};
-
-const visibleText = (html: string): string => html.replace(/<[^>]+>/g, '').replaceAll(TRANSLATION_MARKER, '');
-
-const message = (id: keyof typeof ENGLISH): ReactNode =>
- createElement(Trans, {
- id,
- values: {date: 'Jan 1', price: '$5'},
- components: {0: createElement('strong'), 1: createElement('em')},
- });
-
-const provided = (child: ReactNode, safe: boolean): ReactNode =>
- createElement(safe ? AppI18nProvider : I18nProvider, {i18n}, createElement('div', null, child));
-
-const withBadge = (id: keyof typeof ENGLISH, on: boolean, safe: boolean): ReactNode =>
- provided(
- createElement('div', null, on ? createElement('b', null, '!') : null, message(id), createElement('i', null, 'x')),
- safe,
- );
-
-beforeAll(() => {
- i18n.load('en', ENGLISH);
- i18n.load('de', GERMAN);
- i18n.activate('en');
-});
-
-afterEach(() => {
- i18n.activate('en');
- document.body.replaceChildren();
-});
-
-describe('lingui <Trans> under AppI18nProvider', () => {
- for (const pipelineName of TRANSLATOR_PIPELINE_NAMES) {
- if (pipelineName === 'chromeCompound') {
- for (const id of ['simple', 'rich'] as const) {
- it(`leaves the compound pipeline no text-and-element parent to rewrite in a ${id} message`, () => {
- const unguarded = commitUnderTranslation({
- before: withBadge(id, false, false),
- after: withBadge(id, false, false),
- pipeline: TranslatorPipelines.chromeCompound,
- });
- expect(unguarded.unsafeTextNodesBeforeTranslation).toBeGreaterThan(0);
- expect(unguarded.htmlAfterTranslation).not.toBe(unguarded.htmlBeforeTranslation);
-
- const guarded = commitUnderTranslation({
- before: withBadge(id, false, true),
- after: withBadge(id, true, true),
- pipeline: TranslatorPipelines.chromeCompound,
- });
- expect(guarded.unsafeTextNodesBeforeTranslation).toBe(0);
- expect(guarded.htmlAfterTranslation).toBe(guarded.htmlBeforeTranslation);
- expect(guarded.error).toBeNull();
- });
- }
- continue;
- }
-
- it(`renders a simple message safely under ${pipelineName}`, () => {
- let unsafeTextNodes = -1;
- const result = commitUnderTranslation({
- before: withBadge('simple', false, true),
- after: withBadge('simple', true, true),
- pipeline: TranslatorPipelines[pipelineName],
- inspect: (host) => {
- unsafeTextNodes = findTranslationUnsafeTextNodes(host).length;
- },
- });
- expect(result.htmlAfterTranslation).not.toBe(result.htmlBeforeTranslation);
- expect(result.htmlAfterTranslation).toContain(TRANSLATION_MARKER);
- expect(result.error).toBeNull();
- expect(result.htmlBeforeTranslation).not.toContain('Monthly $5<i>x</i>');
- expect(result.unsafeTextNodesBeforeTranslation).toBe(0);
- expect(unsafeTextNodes).toBe(0);
- expect(visibleText(result.htmlAfterCommit)).toBe('!Monthly $5x');
- });
-
- it(`renders a rich message safely under ${pipelineName}`, () => {
- let unsafeTextNodes = -1;
- const result = commitUnderTranslation({
- before: withBadge('rich', false, true),
- after: withBadge('rich', true, true),
- pipeline: TranslatorPipelines[pipelineName],
- inspect: (host) => {
- unsafeTextNodes = findTranslationUnsafeTextNodes(host).length;
- },
- });
- expect(result.htmlAfterTranslation).not.toBe(result.htmlBeforeTranslation);
- expect(result.htmlAfterTranslation).toContain(TRANSLATION_MARKER);
- expect(result.error).toBeNull();
- expect(unsafeTextNodes).toBe(0);
- expect(result.htmlAfterCommit).toContain('<strong>');
- expect(visibleText(result.htmlAfterCommit)).toBe('!Renews on Jan 1. Enjoy!x');
- });
- }
-});
-
-describe('locale switch while the page is translated', () => {
- for (const id of ['rich', 'nested'] as const) {
- it(`reorders the ${id} message segments without throwing`, () => {
- const result = commitUnderTranslation({
- before: provided(message(id), true),
- after: provided(message(id), true),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- betweenCommits: () => {
- i18n.activate('de');
- },
- });
- expect(result.htmlAfterTranslation).not.toBe(result.htmlBeforeTranslation);
- expect(result.htmlAfterTranslation).toContain(TRANSLATION_MARKER);
- expect(result.error).toBeNull();
- expect(visibleText(result.htmlAfterCommit)).toContain('Viel Spass!');
- });
- }
-});
-
-describe('translation-safe wrapping internals', () => {
- it('recurses into nested rich message elements so no host element mixes text with element children', () => {
- const result = commitUnderTranslation({
- before: provided(message('nested'), true),
- after: provided(message('nested'), true),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- });
- expect(result.unsafeTextNodesBeforeTranslation).toBe(0);
- });
-
- it('remounts on a locale change so no stale translated segment survives', () => {
- const result = commitUnderTranslation({
- before: provided(message('rich'), true),
- after: provided(message('rich'), true),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- betweenCommits: () => {
- i18n.activate('de');
- },
- });
- expect(result.error).toBeNull();
- expect(visibleText(result.htmlAfterCommit)).toContain('Viel Spass!');
- expect(result.htmlAfterCommit.split(TRANSLATION_MARKER).length - 1).toBe(0);
- });
-});
diff --git a/fluxer_app/src/features/i18n/testing/TranslationCommitHarness.ts b/fluxer_app/src/features/i18n/testing/TranslationCommitHarness.ts
deleted file mode 100644
index 30a066b37..000000000
--- a/fluxer_app/src/features/i18n/testing/TranslationCommitHarness.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {findTranslationUnsafeTextNodes} from '@app/features/i18n/testing/TranslatorSimulation';
-import type {ReactNode} from 'react';
-import {flushSync} from 'react-dom';
-import {createRoot} from 'react-dom/client';
-
-export interface TranslationCommitOptions {
- before: ReactNode;
- after: ReactNode;
- pipeline: (root: Element) => void;
- betweenCommits?: () => void;
- inspect?: (host: HTMLElement) => void;
-}
-
-export interface TranslationCommitResult {
- error: Error | null;
- htmlBeforeTranslation: string;
- htmlAfterTranslation: string;
- htmlAfterCommit: string;
- unsafeTextNodesBeforeTranslation: number;
-}
-
-export function commitUnderTranslation({
- before,
- after,
- pipeline,
- betweenCommits,
- inspect,
-}: TranslationCommitOptions): TranslationCommitResult {
- const host = document.createElement('div');
- document.body.appendChild(host);
- let error: Error | null = null;
- const root = createRoot(host, {
- onUncaughtError: (caught) => {
- error ??= caught as Error;
- },
- onCaughtError: (caught) => {
- error ??= caught as Error;
- },
- onRecoverableError: () => {},
- });
- flushSync(() => root.render(before));
- const htmlBeforeTranslation = host.innerHTML;
- const unsafeTextNodesBeforeTranslation = findTranslationUnsafeTextNodes(host).length;
- pipeline(host);
- const htmlAfterTranslation = host.innerHTML;
- try {
- betweenCommits?.();
- } catch (caught) {
- error ??= caught as Error;
- }
- try {
- flushSync(() => root.render(after));
- } catch (caught) {
- error ??= caught as Error;
- }
- const htmlAfterCommit = host.innerHTML;
- inspect?.(host);
- try {
- root.unmount();
- } catch {}
- host.remove();
- return {error, htmlBeforeTranslation, htmlAfterTranslation, htmlAfterCommit, unsafeTextNodesBeforeTranslation};
-}
diff --git a/fluxer_app/src/features/i18n/testing/TranslatorSimulation.ts b/fluxer_app/src/features/i18n/testing/TranslatorSimulation.ts
deleted file mode 100644
index 8557ac246..000000000
--- a/fluxer_app/src/features/i18n/testing/TranslatorSimulation.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-const ELEMENT_NODE = 1;
-const TEXT_NODE = 3;
-
-export const TRANSLATION_MARKER = '~';
-
-const NEVER_TRANSLATED_TAGS = new Set([
- 'SCRIPT',
- 'STYLE',
- 'BR',
- 'WBR',
- 'CODE',
- 'KBD',
- 'MAP',
- 'OBJECT',
- 'PARAM',
- 'RP',
- 'svg',
-]);
-
-function isElement(node: Node): node is Element {
- return node.nodeType === ELEMENT_NODE;
-}
-
-function isNonBlankText(node: Node): boolean {
- return node.nodeType === TEXT_NODE && (node.nodeValue?.trim().length ?? 0) > 0;
-}
-
-function isTranslationOptedOut(element: Element): boolean {
- return (
- NEVER_TRANSLATED_TAGS.has(element.tagName) ||
- element.classList.contains('notranslate') ||
- element.classList.contains('skiptranslate') ||
- element.getAttribute('translate') === 'no'
- );
-}
-
-function walkTranslatable(element: Element, visit: (element: Element) => boolean): void {
- if (isTranslationOptedOut(element)) {
- return;
- }
- if (!visit(element)) {
- return;
- }
- for (const child of Array.from(element.childNodes)) {
- if (isElement(child) && child.tagName !== 'FONT') {
- walkTranslatable(child, visit);
- }
- }
-}
-
-function translatedTextNode(document: Document, source: Node): Text {
- return document.createTextNode(TRANSLATION_MARKER + (source.nodeValue ?? ''));
-}
-
-function reassembledFragment(element: Element, children: ReadonlyArray<Node>): DocumentFragment {
- const document = element.ownerDocument;
- const fragment = document.createDocumentFragment();
- for (const child of children) {
- fragment.appendChild(child.nodeType === TEXT_NODE ? translatedTextNode(document, child) : child.cloneNode(true));
- }
- return fragment;
-}
-
-function wrapTextNodesInFont(element: Element): void {
- const document = element.ownerDocument;
- for (const child of Array.from(element.childNodes)) {
- if (child.nodeType !== TEXT_NODE || !isNonBlankText(child)) {
- continue;
- }
- const outer = document.createElement('font');
- const inner = document.createElement('font');
- outer.setAttribute('style', 'vertical-align: inherit;');
- inner.setAttribute('style', 'vertical-align: inherit;');
- outer.appendChild(inner);
- element.insertBefore(outer, child);
- child.nodeValue = TRANSLATION_MARKER + (child.nodeValue ?? '');
- inner.appendChild(child);
- }
-}
-
-function chromeLegacyFontPipeline(root: Element): void {
- walkTranslatable(root, (element) => {
- wrapTextNodesInFont(element);
- return true;
- });
-}
-
-function chromeCompoundPipeline(root: Element): void {
- walkTranslatable(root, (element) => {
- const children = Array.from(element.childNodes);
- const hasText = children.some(isNonBlankText);
- const hasElement = children.some(isElement);
- if (!hasText || !hasElement) {
- return true;
- }
- element.replaceChildren(reassembledFragment(element, children));
- return false;
- });
-}
-
-function chromeRevertPipeline(root: Element): void {
- const savedChildren = new Map<Element, Array<Node>>();
- walkTranslatable(root, (element) => {
- const children = Array.from(element.childNodes);
- if (children.some(isNonBlankText)) {
- savedChildren.set(element, children);
- }
- return true;
- });
- chromeLegacyFontPipeline(root);
- for (const [element, children] of savedChildren) {
- element.replaceChildren(...children.map((child) => child.cloneNode(true)));
- }
-}
-
-function firefoxMergePipeline(root: Element): void {
- walkTranslatable(root, (element) => {
- const children = Array.from(element.childNodes);
- if (children.length === 0 || !children.some(isNonBlankText)) {
- return true;
- }
- while (element.firstChild) {
- element.removeChild(element.firstChild);
- }
- for (const child of children) {
- element.appendChild(
- child.nodeType === TEXT_NODE ? translatedTextNode(element.ownerDocument, child) : child.cloneNode(true),
- );
- }
- return false;
- });
-}
-
-export const TranslatorPipelines = {
- chromeLegacyFont: chromeLegacyFontPipeline,
- chromeCompound: chromeCompoundPipeline,
- chromeRevert: chromeRevertPipeline,
- firefoxMerge: firefoxMergePipeline,
-} as const;
-
-export type TranslatorPipelineName = keyof typeof TranslatorPipelines;
-
-export const TRANSLATOR_PIPELINE_NAMES = Object.keys(TranslatorPipelines) as Array<TranslatorPipelineName>;
-
-export function findTranslationUnsafeTextNodes(root: Element): Array<Text> {
- const unsafe: Array<Text> = [];
- const visit = (element: Element): void => {
- const children = Array.from(element.childNodes);
- for (const child of children) {
- if (isElement(child)) {
- visit(child);
- } else if (isNonBlankText(child) && children.length > 1) {
- unsafe.push(child as Text);
- }
- }
- };
- visit(root);
- return unsafe;
-}
diff --git a/fluxer_app/src/features/premium/utils/PremiumSubscriptionClassification.test.ts b/fluxer_app/src/features/premium/utils/PremiumSubscriptionClassification.test.ts
deleted file mode 100644
index aa8747dab..000000000
--- a/fluxer_app/src/features/premium/utils/PremiumSubscriptionClassification.test.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- classifyPremiumSubscription,
- type PremiumSubscriptionClassificationInput,
-} from '@app/features/premium/utils/PremiumSubscriptionClassification';
-import {describe, expect, test} from 'vitest';
-
-const NOW = Date.parse('2026-10-08T12:00:00Z');
-const DAY = 24 * 60 * 60 * 1000;
-
-function input(overrides: Partial<PremiumSubscriptionClassificationInput>): PremiumSubscriptionClassificationInput {
- return {
- hasPaidPremium: true,
- isVisionary: false,
- hasStoreSubscription: false,
- billingCycle: null,
- premiumUntil: new Date(NOW + 10 * DAY),
- isInGracePeriod: false,
- isFullyExpired: false,
- billingKnown: true,
- storeOwnershipKnown: true,
- billingSubscription: null,
- ...overrides,
- };
-}
-
-describe('classifyPremiumSubscription', () => {
- test('active gift can start a subscription', () => {
- expect(classifyPremiumSubscription(input({}))).toEqual({
- isGiftSubscription: true,
- isGiftGrace: false,
- canStartSubscription: true,
- });
- });
-
- test('gift grace with no Stripe subscription', () => {
- expect(classifyPremiumSubscription(input({premiumUntil: new Date(NOW - DAY), isInGracePeriod: true}))).toEqual({
- isGiftSubscription: false,
- isGiftGrace: true,
- canStartSubscription: true,
- });
- });
-
- test('gift grace with an old cancelled subscription row', () => {
- expect(
- classifyPremiumSubscription(
- input({
- premiumUntil: new Date(NOW - DAY),
- isInGracePeriod: true,
- billingSubscription: {
- status: 'canceled',
- current_period_end: new Date(NOW - 60 * DAY).toISOString(),
- },
- }),
- ),
- ).toEqual({isGiftSubscription: false, isGiftGrace: true, canStartSubscription: true});
- });
-
- test('payment_failed grace on a past_due subscription', () => {
- expect(
- classifyPremiumSubscription(
- input({
- billingCycle: 'monthly',
- premiumUntil: new Date(NOW - DAY),
- isInGracePeriod: true,
- billingSubscription: {status: 'past_due', current_period_end: new Date(NOW + 29 * DAY).toISOString()},
- }),
- ),
- ).toEqual({isGiftSubscription: false, isGiftGrace: false, canStartSubscription: false});
- });
-
- test('grace after a subscription was deleted for failed payment is not gift grace', () => {
- expect(
- classifyPremiumSubscription(
- input({
- premiumUntil: new Date(NOW - DAY),
- isInGracePeriod: true,
- billingSubscription: {status: 'canceled', current_period_end: new Date(NOW + 29 * DAY).toISOString()},
- }),
- ),
- ).toEqual({isGiftSubscription: false, isGiftGrace: false, canStartSubscription: true});
- });
-
- test('store subscription cannot start a Stripe subscription', () => {
- expect(classifyPremiumSubscription(input({billingCycle: 'monthly', hasStoreSubscription: true}))).toEqual({
- isGiftSubscription: false,
- isGiftGrace: false,
- canStartSubscription: false,
- });
- });
-
- test('lifetime cannot start a subscription', () => {
- expect(classifyPremiumSubscription(input({isVisionary: true, premiumUntil: null}))).toEqual({
- isGiftSubscription: false,
- isGiftGrace: false,
- canStartSubscription: false,
- });
- });
-
- test('active Stripe subscription blocks a new one', () => {
- expect(
- classifyPremiumSubscription(
- input({
- billingCycle: 'yearly',
- billingSubscription: {status: 'active', current_period_end: new Date(NOW + 10 * DAY).toISOString()},
- }),
- ),
- ).toEqual({isGiftSubscription: false, isGiftGrace: false, canStartSubscription: false});
- });
-
- test('unknown billing falls back to the billing cycle', () => {
- expect(
- classifyPremiumSubscription(input({billingKnown: false, billingCycle: 'monthly'})).canStartSubscription,
- ).toBe(false);
- expect(classifyPremiumSubscription(input({billingKnown: false})).canStartSubscription).toBe(true);
- });
-
- test('unknown billing lets a lapsed subscriber resubscribe', () => {
- expect(
- classifyPremiumSubscription(
- input({
- billingKnown: false,
- hasPaidPremium: false,
- billingCycle: 'yearly',
- premiumUntil: new Date(NOW - 35 * DAY),
- isFullyExpired: true,
- }),
- ).canStartSubscription,
- ).toBe(true);
- expect(
- classifyPremiumSubscription(
- input({
- billingKnown: false,
- hasPaidPremium: false,
- billingCycle: 'yearly',
- premiumUntil: new Date(NOW - 5 * DAY),
- isInGracePeriod: true,
- }),
- ),
- ).toEqual({isGiftSubscription: false, isGiftGrace: false, canStartSubscription: true});
- });
-
- test('paid premium cannot start a subscription before store ownership is known', () => {
- expect(
- classifyPremiumSubscription(input({billingKnown: false, storeOwnershipKnown: false})).canStartSubscription,
- ).toBe(false);
- expect(
- classifyPremiumSubscription(
- input({billingKnown: false, storeOwnershipKnown: false, hasPaidPremium: false, premiumUntil: null}),
- ).canStartSubscription,
- ).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/user/hooks/useCustomStatusDraft.test.tsx b/fluxer_app/src/features/user/hooks/useCustomStatusDraft.test.tsx
deleted file mode 100644
index 200426eca..000000000
--- a/fluxer_app/src/features/user/hooks/useCustomStatusDraft.test.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {useCustomStatusDraft} from '@app/features/user/hooks/useCustomStatusDraft';
-import type {CustomStatus} from '@app/features/user/state/CustomStatus';
-import {act} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({update: vi.fn(), limited: vi.fn(() => false), developer: {isDeveloper: false}}));
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-vi.mock('@lingui/react/macro', () => ({
- useLingui: () => ({i18n: {locale: 'en', _: (d: {message: string}) => d.message}}),
-}));
-vi.mock('@app/features/app/config/TimeWindowPresets', () => ({
- getTimeWindowPresets: ({includeDeveloperOptions}: {includeDeveloperOptions: boolean}) => [
- {key: 'never', minutes: null},
- ...(includeDeveloperOptions ? [{key: 'minute', minutes: 1}] : []),
- {key: 'half_hour', minutes: 30},
- ],
- TIME_WINDOW_LABEL_MESSAGES: {
- never: {message: 'Never'},
- minute: {message: 'One minute'},
- half_hour: {message: '30 minutes'},
- },
-}));
-vi.mock('@app/features/app/hooks/useShouldAnimate', () => ({useShouldAnimate: () => false}));
-vi.mock('@app/features/devtools/state/DeveloperMode', () => ({default: mocks.developer}));
-vi.mock('@app/features/emoji/state/Emoji', () => ({default: {getEmojiById: () => null}}));
-vi.mock('@app/features/expressions/utils/CustomEmojiImageUrl', () => ({buildCustomEmojiURL: () => ''}));
-vi.mock('@app/features/expressions/utils/EmojiUtils', () => ({getEmojiURL: () => null}));
-vi.mock('@app/features/expressions/utils/SkinToneUtils', () => ({getSkinTonedSurrogate: () => '🙂'}));
-vi.mock('@app/features/user/commands/UserSettingsCommands', () => ({update: mocks.update}));
-vi.mock('@app/features/user/utils/AccountLimitUtils', () => ({handleAccountLimitedError: mocks.limited}));
-
-let root: Root;
-let node: HTMLDivElement;
-let draft: ReturnType<typeof useCustomStatusDraft>;
-let expiresAt: string | null;
-const saved = vi.fn();
-function Probe({initialStatus = null}: {initialStatus?: CustomStatus | null}) {
- draft = useCustomStatusDraft({initialStatus, onSaved: saved, getExpiresAt: () => expiresAt});
- return null;
-}
-beforeEach(async () => {
- vi.clearAllMocks();
- mocks.developer.isDeveloper = false;
- expiresAt = null;
- node = document.createElement('div');
- document.body.append(node);
- root = createRoot(node);
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- await act(async () => {
- root.render(<Probe data-flx="user.use-custom-status-draft-test.probe" />);
- });
-});
-afterEach(async () => {
- await act(async () => root.unmount());
- node.remove();
-});
-describe('custom status draft lifecycle', () => {
- it('reinitializes drafts on reopen without retaining edited emoji or text', async () => {
- await act(async () => {
- draft.setStatusText('edited');
- draft.handleEmojiSelect({id: 'custom', name: 'wave'} as never);
- });
- expect(draft.draftStatus?.emojiId).toBe('custom');
- const initial = {text: 'Original', emojiId: null, emojiName: '🙂', expiresAt: null};
- await act(async () => draft.resetDraft(initial));
- expect(draft.statusText).toBe('Original');
- expect(draft.draftStatus).toMatchObject({text: 'Original', emojiId: null, emojiName: '🙂'});
- await act(async () => draft.handleClearDraft());
- expect(draft.draftStatus).toBeNull();
- });
- it('saves with the current expiry and closes only after the server accepts the draft', async () => {
- let finish!: () => void;
- mocks.update.mockReturnValueOnce(
- new Promise<void>((resolve) => {
- finish = resolve;
- }),
- );
- await act(async () => draft.setStatusText(' Away '));
- expiresAt = '2030-01-01T00:00:00.000Z';
- let pending!: Promise<void>;
- await act(async () => {
- pending = draft.handleSave();
- });
- expect(draft.isSaving).toBe(true);
- expect(saved).not.toHaveBeenCalled();
- expect(mocks.update).toHaveBeenCalledWith({customStatus: expect.objectContaining({text: 'Away', expiresAt})});
- await act(async () => draft.handleSave());
- expect(mocks.update).toHaveBeenCalledOnce();
- await act(async () => {
- finish();
- await pending;
- });
- expect(saved).toHaveBeenCalledOnce();
- expect(draft.isSaving).toBe(false);
- });
- it('keeps a rejected draft open and clears its saving state', async () => {
- const failure = new Error('limited');
- mocks.update.mockRejectedValueOnce(failure);
- mocks.limited.mockReturnValueOnce(true);
- await act(async () => draft.setStatusText('Busy'));
- await act(async () => draft.handleSave());
- expect(mocks.limited).toHaveBeenCalledWith(failure);
- expect(saved).not.toHaveBeenCalled();
- expect(draft.isSaving).toBe(false);
- expect(draft.statusText).toBe('Busy');
- });
-});
diff --git a/fluxer_app/src/features/user/state/UserSettingsTransitionFlush.test.ts b/fluxer_app/src/features/user/state/UserSettingsTransitionFlush.test.ts
deleted file mode 100644
index 23c63c516..000000000
--- a/fluxer_app/src/features/user/state/UserSettingsTransitionFlush.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({patch: vi.fn()}));
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: unknown) => descriptor,
- t: (descriptor: unknown) => descriptor,
-}));
-
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {get: vi.fn(), post: vi.fn(), patch: mocks.patch},
-}));
-
-const {AccountScopedWork, AccountScopedWorkTransitionReason, accountScopedWorkAbortError} = await import(
- '@app/features/platform/state/AccountScopedWork'
-);
-const {default: UserSettings} = await import('@app/features/user/state/UserSettings');
-
-async function settle(): Promise<void> {
- for (let i = 0; i < 10; i++) {
- await Promise.resolve();
- }
- await new Promise((resolve) => setTimeout(resolve, 0));
-}
-
-function hydrate(): void {
- UserSettings.updateUserSettings({
- status: 'online',
- flags: 0,
- locale: 'en-US',
- developer_mode: false,
- message_display_compact: false,
- restricted_guilds: [],
- bot_restricted_guilds: [],
- guild_folders: [],
- trusted_domains: [],
- staff_dm_access_user_ids: [],
- suppress_unprivileged_self_mentions_bypass_user_ids: [],
- });
-}
-
-describe('UserSettings synced preference flush across account transitions', () => {
- afterEach(() => {
- UserSettings.handleAccountTransition();
- mocks.patch.mockReset();
- });
-
- it('holds a flush requested during a transition until admission opens', async () => {
- hydrate();
- mocks.patch.mockResolvedValue({ok: true, status: 200, body: {}});
- let saved: Promise<void> | null = null;
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- saved = UserSettings.setSanitizeUrls(!UserSettings.getSanitizeUrls());
- await settle();
- expect(mocks.patch).not.toHaveBeenCalled();
- });
- await settle();
- expect(mocks.patch).toHaveBeenCalledTimes(1);
- await expect(saved).resolves.toBeUndefined();
- });
-
- it('retries a flush aborted by an account transition instead of failing it', async () => {
- hydrate();
- mocks.patch.mockRejectedValueOnce(accountScopedWorkAbortError());
- mocks.patch.mockResolvedValue({ok: true, status: 200, body: {}});
- const saved = UserSettings.setSanitizeUrls(!UserSettings.getSanitizeUrls());
- await settle();
- expect(mocks.patch).toHaveBeenCalledTimes(2);
- await expect(saved).resolves.toBeUndefined();
- });
-});
diff --git a/fluxer_app/src/features/user/utils/MessagingPausedHelpEmail.test.ts b/fluxer_app/src/features/user/utils/MessagingPausedHelpEmail.test.ts
deleted file mode 100644
index 793dd4eb1..000000000
--- a/fluxer_app/src/features/user/utils/MessagingPausedHelpEmail.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {buildMessagingPausedHelpEmail} from '@app/features/user/utils/MessagingPausedHelpEmail';
-import type {I18n} from '@lingui/core';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: unknown) => descriptor,
-}));
-
-const i18n = {
- _: (descriptor: {message: string}, values: Record<string, string> = {}) =>
- descriptor.message.replace(/\{(\w+)\}/g, (_match, key: string) => values[key] ?? ''),
-} as unknown as I18n;
-
-describe('buildMessagingPausedHelpEmail', () => {
- it('fills the support email with the account facts', () => {
- const {body, mailto} = buildMessagingPausedHelpEmail(
- i18n,
- {id: '1425000000000000000', tag: 'marty#0001', createdAt: new Date('2026-10-07T12:30:00.000Z')},
- ' Philippines ',
- );
- expect(body).toBe(
- [
- "My text didn't go through",
- '',
- 'Account ID: 1425000000000000000',
- 'Username: marty#0001',
- 'Account created: 2026-10-07T12:30:00.000Z',
- 'Country: Philippines',
- ].join('\n'),
- );
- const url = new URL(mailto);
- expect(url.protocol).toBe('mailto:');
- expect(url.pathname).toBe('[email protected]');
- expect(url.searchParams.get('subject')).toBe("My text didn't go through");
- expect(decodeURIComponent(mailto.split('&body=')[1])).toBe(body);
- });
-});