Files
OpenFrontIO/tests/client/clan/ClanModalTestUtils.ts
T
Evan Pelle a7f992e9b0 refactor: convert to npm-workspaces monorepo (engine/core-public/shared/client/server)
Restructure the single src/ tree into an npm-workspaces monorepo under
packages/, rename core -> engine, extract a types-only core-public layer,
and break the pre-existing engine -> client dependency cycle.

Structure (packages/):
  core-public  public API/wire schemas + shared enums (clean leaf)
  shared       framework-agnostic helpers (clean leaf)
  engine       deterministic simulation (was src/core)
  client       rendering/UI (was src/client)
  server       coordination (was src/server)

Dependency DAG: engine -> {core-public, shared}; client -> {core-public,
shared, engine}; server -> {core-public, engine}.

- npm workspaces: root package.json workspaces + per-package package.json;
  tsconfig.base.json holds shared options + path aliases
  (core-public/* shared/* engine/* client/* server/*) resolved uniformly by
  tsc, Vite (resolve.tsconfigPaths), Vitest, and tsx. Lockfile regenerated.
- core-public: moved Schemas/ApiSchemas/CosmeticSchemas/StatsSchemas/
  ClanApiSchemas/WorkerSchemas/Base64/PatternDecoder; extracted the enums
  (GameTypes), GameEvent type, emoji table, and GraphicsOverrides schema.
  Engine re-exports the moved enums/types so existing imports keep working.
- Broke engine -> client cycle:
  - renderNumber/renderTroops -> shared/format
  - NameBoxCalculator moved into engine
  - username validation returns translation key + params; client translates
  - applyStateUpdate moved to client (operates on the render-only PlayerState)
  - Config/UnitGrid/execution-Util/GameImpl now use structural read
    interfaces (engine/game/ReadViews: PlayerLike/UnitLike/GameLike) instead
    of importing client view classes; client imports view classes from a new
    client/view barrel; deleted the engine/game/GameView re-export shim.
- Build/deploy updated: vite.config, index.html, eslint, Dockerfile
  (copies packages/ + tsconfig.base.json before npm ci), .vscode, tests.

Verified: tsc --noEmit clean; 1364 + 65 tests pass; production vite build
succeeds; engine has zero client/server imports; core-public and shared are
dependency leaves.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 16:51:03 +00:00

200 lines
5.4 KiB
TypeScript

import { vi } from "vitest";
import type { ClanInfo } from "client/ClanApi";
import type { ClanModal } from "client/ClanModal";
// ─── Mock factories ─────────────────────────────────────────────────────────
// Each factory returns a fresh object of vi.fn()s. Test files pass these to
// vi.mock() so Vitest invokes them when the mocked module is first imported.
// The factory pattern keeps the mock surface DRY across test files while
// preserving per-file module isolation.
export function clanApiMockFactory() {
return {
fetchClanDetail: vi.fn(async () => ({
name: "Test Clan",
tag: "TST",
description: "A test clan",
isOpen: true,
createdAt: "2024-01-01T00:00:00Z",
memberCount: 5,
})),
fetchClanMembers: vi.fn(async () => ({
results: [
{
role: "leader",
joinedAt: "2024-01-01T00:00:00Z",
publicId: "test-player",
},
],
total: 1,
page: 1,
limit: 10,
pendingRequests: 0,
})),
fetchClans: vi.fn(async () => ({
results: [],
total: 0,
page: 1,
limit: 20,
})),
joinClan: vi.fn(),
leaveClan: vi.fn(),
updateClan: vi.fn(),
disbandClan: vi.fn(),
kickMember: vi.fn(),
promoteMember: vi.fn(),
demoteMember: vi.fn(),
transferLeadership: vi.fn(),
fetchClanRequests: vi.fn(async () => ({
results: [],
total: 0,
page: 1,
limit: 20,
})),
approveClanRequest: vi.fn(async () => true),
denyClanRequest: vi.fn(),
withdrawClanRequest: vi.fn(),
fetchClanLeaderboard: vi.fn(),
banClanMember: vi.fn(async () => true),
unbanClanMember: vi.fn(async () => true),
fetchClanBans: vi.fn(async () => ({
results: [],
total: 0,
page: 1,
limit: 20,
})),
fetchClanGames: vi.fn(async () => ({
results: [],
nextCursor: null,
})),
};
}
export function apiMockFactory() {
return {
getUserMe: vi.fn(async () => ({
player: {
publicId: "test-player",
clans: [
{
tag: "TST",
name: "Test Clan",
role: "leader",
joinedAt: "2024-01-01T00:00:00Z",
memberCount: 5,
},
],
clanRequests: [],
achievements: { singleplayerMap: [] },
},
user: { email: "test@test.com" },
})),
invalidateUserMe: vi.fn(),
};
}
export function utilsMockFactory() {
return {
translateText: vi.fn((key: string) => key),
showToast: vi.fn(),
};
}
export function authMockFactory() {
return {
getAuthHeader: vi.fn(async () => "Bearer test-token"),
userAuth: vi.fn(async () => ({ jwt: "test-token", claims: {} })),
};
}
export function crazyGamesSdkMockFactory() {
return {
crazyGamesSDK: { isAvailable: false },
};
}
export async function virtualizerMockFactory() {
const { html } = await import("lit");
return {
virtualize: vi.fn(() => html``),
};
}
export function stubLocalStorage() {
vi.stubGlobal("localStorage", {
getItem: vi.fn(() => null),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
});
}
// ─── Test helpers ───────────────────────────────────────────────────────────
/**
* Drain pending microtasks and Lit's update scheduler.
* Replaces bare `await new Promise(r => setTimeout(r, 0))` which only drains
* a single microtask tick and can miss batched Lit updates.
*/
export async function flushAsync(
...els: (Element | null | undefined)[]
): Promise<void> {
// Two ticks to drain chained microtasks (e.g. async handler → state update → re-render).
await new Promise((r) => setTimeout(r, 0));
await new Promise((r) => setTimeout(r, 0));
for (const el of els) {
if (el && "updateComplete" in el) {
await (el as HTMLElement & { updateComplete: Promise<boolean> })
.updateComplete;
}
}
}
/** Force-set a Lit @state property and trigger re-render. */
export function setState<K extends keyof ClanModal>(
modal: ClanModal,
key: K,
value: ClanModal[K],
) {
(modal as unknown as Record<string, unknown>)[key] = value;
}
/** Force-set a property on any element (sub-components etc.). */
export function setElState(el: Element, key: string, value: unknown) {
(el as unknown as Record<string, unknown>)[key] = value;
}
/** Get a property from any element. */
export function getElState<T = unknown>(el: Element, key: string): T {
return (el as unknown as Record<string, unknown>)[key] as T;
}
/**
* Wait for a sub-component to mount and finish its initial async load.
* Call after setting ClanModal state that causes the sub-component to render.
*/
export async function waitForSubComponent(
modal: ClanModal,
selector: string,
): Promise<Element> {
await flushAsync(modal);
const el = modal.querySelector(selector)!;
if (el && "updateComplete" in el) {
await (el as HTMLElement & { updateComplete: Promise<boolean> })
.updateComplete;
}
return el;
}
export function makeClan(overrides: Partial<ClanInfo> = {}): ClanInfo {
return {
name: "Test Clan",
tag: "TST",
description: "A test clan",
isOpen: true,
createdAt: "2024-01-01T00:00:00Z",
memberCount: 5,
...overrides,
};
}