phase 8: lobby UI + cross-stack lobby command catalog + TS FlatBuffers
- Extend pkg/model/lobby and pkg/schema/fbs/lobby.fbs with public-games
list, my-applications/invites lists, game-create, application-submit,
invite-redeem/decline. Mirror the matching transcoder pairs and Go
fixture round-trip tests.
- Wire the seven new lobby message types through
gateway/internal/backendclient/{routes,lobby_commands}.go with
per-command REST helpers, JSON-tolerant decoding of backend wire
shapes, and httptest-based unit coverage for success / 4xx / 5xx /
503 across each command.
- Introduce TS-side FlatBuffers via the `flatbuffers` runtime dep, a
`make fbs-ts` target driving flatc, and the generated bindings under
ui/frontend/src/proto/galaxy/fbs. Phase 7's `user.account.get` decode
now uses these bindings as well, closing the JSON.parse vs
FlatBuffers gap that would have failed against a real local stack.
- Replace the placeholder lobby with five sections (my games, pending
invitations, my applications, public games, create new game) and the
/lobby/create form. Submit-application uses an inline race-name
form on the public-game card; create-game keeps name / description /
turn_schedule / enrollment_ends_at always visible and the rest under
an Advanced toggle with TS-side defaults.
- Update lobby/+page.svelte to throw LobbyError on non-ok result codes;
GalaxyClient.executeCommand now returns { resultCode, payloadBytes }.
- Vitest binding round-trips, lobby.ts wrapper unit tests, lobby-page
+ lobby-create component tests, Playwright lobby-flow.spec covering
create / submit / accept across all four projects. Phase 7 e2e was
migrated to the FlatBuffers fixtures and to click+fill against the
Safari-autofill readonly inputs.
- Mark Phase 8 done in ui/PLAN.md, mirror the wire-format note into
Phase 7, append the new lobby commands to gateway/README.md and
docs/ARCHITECTURE.md, add ui/docs/lobby.md.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,13 @@ import { fromJson, type JsonValue } from "@bufbuild/protobuf";
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { ExecuteCommandRequestSchema } from "../../src/proto/galaxy/gateway/v1/edge_gateway_pb";
|
||||
import { forgeExecuteCommandResponseJson } from "./fixtures/sign-response";
|
||||
import {
|
||||
buildAccountResponsePayload,
|
||||
buildMyApplicationsListPayload,
|
||||
buildMyGamesListPayload,
|
||||
buildMyInvitesListPayload,
|
||||
buildPublicGamesListPayload,
|
||||
} from "./fixtures/lobby-fbs";
|
||||
|
||||
interface MockSetup {
|
||||
pendingSubscribes: Array<() => void>;
|
||||
@@ -58,19 +65,36 @@ async function mockGatewayHappyPath(
|
||||
ExecuteCommandRequestSchema,
|
||||
JSON.parse(reqText) as JsonValue,
|
||||
);
|
||||
const accountJson = JSON.stringify({
|
||||
account: {
|
||||
user_id: "user-1",
|
||||
email: "pilot@example.com",
|
||||
user_name: "player-test",
|
||||
display_name: displayName,
|
||||
},
|
||||
});
|
||||
let payload: Uint8Array;
|
||||
switch (req.messageType) {
|
||||
case "user.account.get":
|
||||
payload = buildAccountResponsePayload({
|
||||
userId: "user-1",
|
||||
email: "pilot@example.com",
|
||||
userName: "player-test",
|
||||
displayName,
|
||||
});
|
||||
break;
|
||||
case "lobby.my.games.list":
|
||||
payload = buildMyGamesListPayload([]);
|
||||
break;
|
||||
case "lobby.public.games.list":
|
||||
payload = buildPublicGamesListPayload([]);
|
||||
break;
|
||||
case "lobby.my.invites.list":
|
||||
payload = buildMyInvitesListPayload([]);
|
||||
break;
|
||||
case "lobby.my.applications.list":
|
||||
payload = buildMyApplicationsListPayload([]);
|
||||
break;
|
||||
default:
|
||||
payload = new Uint8Array();
|
||||
}
|
||||
const responseJson = await forgeExecuteCommandResponseJson({
|
||||
requestId: req.requestId,
|
||||
timestampMs: BigInt(Date.now()),
|
||||
resultCode: "ok",
|
||||
payloadBytes: new TextEncoder().encode(accountJson),
|
||||
payloadBytes: payload,
|
||||
});
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
@@ -122,9 +146,14 @@ async function mockGatewayHappyPath(
|
||||
async function completeLogin(page: Page): Promise<void> {
|
||||
await page.goto("/");
|
||||
await expect(page).toHaveURL(/\/login$/);
|
||||
// Inputs render `readonly` initially as a Safari autofill-suppression
|
||||
// workaround; the attribute drops on first focus. Click first so the
|
||||
// onfocus handler runs before fill checks editability.
|
||||
await page.getByTestId("login-email-input").click();
|
||||
await page.getByTestId("login-email-input").fill("pilot@example.com");
|
||||
await page.getByTestId("login-email-submit").click();
|
||||
await expect(page.getByTestId("login-code-input")).toBeVisible();
|
||||
await page.getByTestId("login-code-input").click();
|
||||
await page.getByTestId("login-code-input").fill("123456");
|
||||
await page.getByTestId("login-code-submit").click();
|
||||
await expect(page).toHaveURL(/\/lobby$/);
|
||||
@@ -213,6 +242,7 @@ test.describe("Phase 7 — auth flow", () => {
|
||||
"отправить код",
|
||||
);
|
||||
|
||||
await page.getByTestId("login-email-input").click();
|
||||
await page.getByTestId("login-email-input").fill("pilot@example.com");
|
||||
await page.getByTestId("login-email-submit").click();
|
||||
await expect(page.getByTestId("login-code-input")).toBeVisible();
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
// Helpers that build FlatBuffers payloads for the lobby Playwright
|
||||
// suite. Mirrors what `pkg/transcoder/lobby.go` produces in production,
|
||||
// so the forged response goes through the same TS decoder the lobby
|
||||
// page uses.
|
||||
|
||||
import { Builder } from "flatbuffers";
|
||||
|
||||
import {
|
||||
AccountResponse,
|
||||
AccountView,
|
||||
EntitlementSnapshot,
|
||||
} from "../../../src/proto/galaxy/fbs/user";
|
||||
import {
|
||||
ApplicationSubmitResponse,
|
||||
ApplicationSummary,
|
||||
GameCreateResponse,
|
||||
GameSummary,
|
||||
InviteDeclineResponse,
|
||||
InviteRedeemResponse,
|
||||
InviteSummary,
|
||||
MyApplicationsListResponse,
|
||||
MyGamesListResponse,
|
||||
MyInvitesListResponse,
|
||||
PublicGamesListResponse,
|
||||
} from "../../../src/proto/galaxy/fbs/lobby";
|
||||
|
||||
export interface GameFixture {
|
||||
gameId: string;
|
||||
gameName: string;
|
||||
gameType: string;
|
||||
status: string;
|
||||
ownerUserId?: string;
|
||||
minPlayers?: number;
|
||||
maxPlayers?: number;
|
||||
enrollmentEndsAtMs?: bigint;
|
||||
createdAtMs?: bigint;
|
||||
updatedAtMs?: bigint;
|
||||
}
|
||||
|
||||
export interface ApplicationFixture {
|
||||
applicationId: string;
|
||||
gameId: string;
|
||||
applicantUserId: string;
|
||||
raceName: string;
|
||||
status: string;
|
||||
createdAtMs?: bigint;
|
||||
decidedAtMs?: bigint;
|
||||
}
|
||||
|
||||
export interface InviteFixture {
|
||||
inviteId: string;
|
||||
gameId: string;
|
||||
inviterUserId: string;
|
||||
invitedUserId?: string;
|
||||
code?: string;
|
||||
raceName: string;
|
||||
status: string;
|
||||
createdAtMs?: bigint;
|
||||
expiresAtMs?: bigint;
|
||||
decidedAtMs?: bigint;
|
||||
}
|
||||
|
||||
const DEFAULT_TIME_MS = 1_780_000_000_000n;
|
||||
|
||||
function encodeGame(builder: Builder, game: GameFixture): number {
|
||||
const gameId = builder.createString(game.gameId);
|
||||
const gameName = builder.createString(game.gameName);
|
||||
const gameType = builder.createString(game.gameType);
|
||||
const status = builder.createString(game.status);
|
||||
const ownerUserId = builder.createString(game.ownerUserId ?? "");
|
||||
GameSummary.startGameSummary(builder);
|
||||
GameSummary.addGameId(builder, gameId);
|
||||
GameSummary.addGameName(builder, gameName);
|
||||
GameSummary.addGameType(builder, gameType);
|
||||
GameSummary.addStatus(builder, status);
|
||||
GameSummary.addOwnerUserId(builder, ownerUserId);
|
||||
GameSummary.addMinPlayers(builder, game.minPlayers ?? 2);
|
||||
GameSummary.addMaxPlayers(builder, game.maxPlayers ?? 8);
|
||||
GameSummary.addEnrollmentEndsAtMs(builder, game.enrollmentEndsAtMs ?? DEFAULT_TIME_MS);
|
||||
GameSummary.addCreatedAtMs(builder, game.createdAtMs ?? DEFAULT_TIME_MS);
|
||||
GameSummary.addUpdatedAtMs(builder, game.updatedAtMs ?? DEFAULT_TIME_MS);
|
||||
return GameSummary.endGameSummary(builder);
|
||||
}
|
||||
|
||||
function encodeApplication(builder: Builder, app: ApplicationFixture): number {
|
||||
const applicationId = builder.createString(app.applicationId);
|
||||
const gameId = builder.createString(app.gameId);
|
||||
const applicantUserId = builder.createString(app.applicantUserId);
|
||||
const raceName = builder.createString(app.raceName);
|
||||
const status = builder.createString(app.status);
|
||||
ApplicationSummary.startApplicationSummary(builder);
|
||||
ApplicationSummary.addApplicationId(builder, applicationId);
|
||||
ApplicationSummary.addGameId(builder, gameId);
|
||||
ApplicationSummary.addApplicantUserId(builder, applicantUserId);
|
||||
ApplicationSummary.addRaceName(builder, raceName);
|
||||
ApplicationSummary.addStatus(builder, status);
|
||||
ApplicationSummary.addCreatedAtMs(builder, app.createdAtMs ?? DEFAULT_TIME_MS);
|
||||
ApplicationSummary.addDecidedAtMs(builder, app.decidedAtMs ?? 0n);
|
||||
return ApplicationSummary.endApplicationSummary(builder);
|
||||
}
|
||||
|
||||
function encodeInvite(builder: Builder, invite: InviteFixture): number {
|
||||
const inviteId = builder.createString(invite.inviteId);
|
||||
const gameId = builder.createString(invite.gameId);
|
||||
const inviterUserId = builder.createString(invite.inviterUserId);
|
||||
const invitedUserId = builder.createString(invite.invitedUserId ?? "");
|
||||
const code = builder.createString(invite.code ?? "");
|
||||
const raceName = builder.createString(invite.raceName);
|
||||
const status = builder.createString(invite.status);
|
||||
InviteSummary.startInviteSummary(builder);
|
||||
InviteSummary.addInviteId(builder, inviteId);
|
||||
InviteSummary.addGameId(builder, gameId);
|
||||
InviteSummary.addInviterUserId(builder, inviterUserId);
|
||||
InviteSummary.addInvitedUserId(builder, invitedUserId);
|
||||
InviteSummary.addCode(builder, code);
|
||||
InviteSummary.addRaceName(builder, raceName);
|
||||
InviteSummary.addStatus(builder, status);
|
||||
InviteSummary.addCreatedAtMs(builder, invite.createdAtMs ?? DEFAULT_TIME_MS);
|
||||
InviteSummary.addExpiresAtMs(builder, invite.expiresAtMs ?? DEFAULT_TIME_MS);
|
||||
InviteSummary.addDecidedAtMs(builder, invite.decidedAtMs ?? 0n);
|
||||
return InviteSummary.endInviteSummary(builder);
|
||||
}
|
||||
|
||||
export function buildMyGamesListPayload(games: GameFixture[]): Uint8Array {
|
||||
const builder = new Builder(256);
|
||||
const offsets = games.map((g) => encodeGame(builder, g));
|
||||
const items = MyGamesListResponse.createItemsVector(builder, offsets);
|
||||
MyGamesListResponse.startMyGamesListResponse(builder);
|
||||
MyGamesListResponse.addItems(builder, items);
|
||||
builder.finish(MyGamesListResponse.endMyGamesListResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
|
||||
export function buildPublicGamesListPayload(
|
||||
games: GameFixture[],
|
||||
page = 1,
|
||||
pageSize = 50,
|
||||
): Uint8Array {
|
||||
const builder = new Builder(256);
|
||||
const offsets = games.map((g) => encodeGame(builder, g));
|
||||
const items = PublicGamesListResponse.createItemsVector(builder, offsets);
|
||||
PublicGamesListResponse.startPublicGamesListResponse(builder);
|
||||
PublicGamesListResponse.addItems(builder, items);
|
||||
PublicGamesListResponse.addPage(builder, page);
|
||||
PublicGamesListResponse.addPageSize(builder, pageSize);
|
||||
PublicGamesListResponse.addTotal(builder, games.length);
|
||||
builder.finish(PublicGamesListResponse.endPublicGamesListResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
|
||||
export function buildMyApplicationsListPayload(
|
||||
applications: ApplicationFixture[],
|
||||
): Uint8Array {
|
||||
const builder = new Builder(256);
|
||||
const offsets = applications.map((a) => encodeApplication(builder, a));
|
||||
const items = MyApplicationsListResponse.createItemsVector(builder, offsets);
|
||||
MyApplicationsListResponse.startMyApplicationsListResponse(builder);
|
||||
MyApplicationsListResponse.addItems(builder, items);
|
||||
builder.finish(MyApplicationsListResponse.endMyApplicationsListResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
|
||||
export function buildMyInvitesListPayload(invites: InviteFixture[]): Uint8Array {
|
||||
const builder = new Builder(256);
|
||||
const offsets = invites.map((i) => encodeInvite(builder, i));
|
||||
const items = MyInvitesListResponse.createItemsVector(builder, offsets);
|
||||
MyInvitesListResponse.startMyInvitesListResponse(builder);
|
||||
MyInvitesListResponse.addItems(builder, items);
|
||||
builder.finish(MyInvitesListResponse.endMyInvitesListResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
|
||||
export function buildGameCreateResponsePayload(game: GameFixture): Uint8Array {
|
||||
const builder = new Builder(256);
|
||||
const summary = encodeGame(builder, game);
|
||||
GameCreateResponse.startGameCreateResponse(builder);
|
||||
GameCreateResponse.addGame(builder, summary);
|
||||
builder.finish(GameCreateResponse.endGameCreateResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
|
||||
export function buildApplicationSubmitResponsePayload(
|
||||
application: ApplicationFixture,
|
||||
): Uint8Array {
|
||||
const builder = new Builder(128);
|
||||
const app = encodeApplication(builder, application);
|
||||
ApplicationSubmitResponse.startApplicationSubmitResponse(builder);
|
||||
ApplicationSubmitResponse.addApplication(builder, app);
|
||||
builder.finish(ApplicationSubmitResponse.endApplicationSubmitResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
|
||||
export function buildInviteRedeemResponsePayload(invite: InviteFixture): Uint8Array {
|
||||
const builder = new Builder(128);
|
||||
const summary = encodeInvite(builder, invite);
|
||||
InviteRedeemResponse.startInviteRedeemResponse(builder);
|
||||
InviteRedeemResponse.addInvite(builder, summary);
|
||||
builder.finish(InviteRedeemResponse.endInviteRedeemResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
|
||||
export function buildInviteDeclineResponsePayload(invite: InviteFixture): Uint8Array {
|
||||
const builder = new Builder(128);
|
||||
const summary = encodeInvite(builder, invite);
|
||||
InviteDeclineResponse.startInviteDeclineResponse(builder);
|
||||
InviteDeclineResponse.addInvite(builder, summary);
|
||||
builder.finish(InviteDeclineResponse.endInviteDeclineResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
|
||||
export interface AccountFixture {
|
||||
userId: string;
|
||||
email: string;
|
||||
userName: string;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
export function buildAccountResponsePayload(account: AccountFixture): Uint8Array {
|
||||
const builder = new Builder(256);
|
||||
|
||||
const planCode = builder.createString("free");
|
||||
const source = builder.createString("internal");
|
||||
const reasonCode = builder.createString("");
|
||||
EntitlementSnapshot.startEntitlementSnapshot(builder);
|
||||
EntitlementSnapshot.addPlanCode(builder, planCode);
|
||||
EntitlementSnapshot.addIsPaid(builder, false);
|
||||
EntitlementSnapshot.addSource(builder, source);
|
||||
EntitlementSnapshot.addReasonCode(builder, reasonCode);
|
||||
EntitlementSnapshot.addStartsAtMs(builder, 0n);
|
||||
EntitlementSnapshot.addEndsAtMs(builder, 0n);
|
||||
EntitlementSnapshot.addUpdatedAtMs(builder, 0n);
|
||||
const entitlement = EntitlementSnapshot.endEntitlementSnapshot(builder);
|
||||
|
||||
const userId = builder.createString(account.userId);
|
||||
const email = builder.createString(account.email);
|
||||
const userName = builder.createString(account.userName);
|
||||
const displayName = builder.createString(account.displayName);
|
||||
const preferredLanguage = builder.createString("en");
|
||||
const timeZone = builder.createString("UTC");
|
||||
const declaredCountry = builder.createString("");
|
||||
AccountView.startAccountView(builder);
|
||||
AccountView.addUserId(builder, userId);
|
||||
AccountView.addEmail(builder, email);
|
||||
AccountView.addUserName(builder, userName);
|
||||
AccountView.addDisplayName(builder, displayName);
|
||||
AccountView.addPreferredLanguage(builder, preferredLanguage);
|
||||
AccountView.addTimeZone(builder, timeZone);
|
||||
AccountView.addDeclaredCountry(builder, declaredCountry);
|
||||
AccountView.addEntitlement(builder, entitlement);
|
||||
AccountView.addCreatedAtMs(builder, 0n);
|
||||
AccountView.addUpdatedAtMs(builder, 0n);
|
||||
const view = AccountView.endAccountView(builder);
|
||||
|
||||
AccountResponse.startAccountResponse(builder);
|
||||
AccountResponse.addAccount(builder, view);
|
||||
builder.finish(AccountResponse.endAccountResponse(builder));
|
||||
return builder.asUint8Array();
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
// Phase 8 lobby end-to-end coverage. The gateway is mocked through
|
||||
// `page.route(...)` like in the Phase 7 spec; this spec dispatches by
|
||||
// `messageType` so each lobby command can return its own forged
|
||||
// FlatBuffers payload. The flows under test:
|
||||
//
|
||||
// 1) Land on /lobby with empty lists; create a private game; verify
|
||||
// the new game appears in My Games after the redirect.
|
||||
// 2) Submit an application to a public game; verify the application
|
||||
// shows up in My Applications.
|
||||
// 3) Accept an invitation; verify the invite card disappears.
|
||||
|
||||
import { fromJson, type JsonValue } from "@bufbuild/protobuf";
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { ByteBuffer } from "flatbuffers";
|
||||
import { ExecuteCommandRequestSchema } from "../../src/proto/galaxy/gateway/v1/edge_gateway_pb";
|
||||
import { GameCreateRequest } from "../../src/proto/galaxy/fbs/lobby";
|
||||
import { forgeExecuteCommandResponseJson } from "./fixtures/sign-response";
|
||||
import {
|
||||
buildAccountResponsePayload,
|
||||
buildApplicationSubmitResponsePayload,
|
||||
buildGameCreateResponsePayload,
|
||||
buildInviteRedeemResponsePayload,
|
||||
buildMyApplicationsListPayload,
|
||||
buildMyGamesListPayload,
|
||||
buildMyInvitesListPayload,
|
||||
buildPublicGamesListPayload,
|
||||
type ApplicationFixture,
|
||||
type GameFixture,
|
||||
type InviteFixture,
|
||||
} from "./fixtures/lobby-fbs";
|
||||
|
||||
interface LobbyState {
|
||||
myGames: GameFixture[];
|
||||
publicGames: GameFixture[];
|
||||
invitations: InviteFixture[];
|
||||
applications: ApplicationFixture[];
|
||||
}
|
||||
|
||||
interface LobbyMocks {
|
||||
state: LobbyState;
|
||||
pendingSubscribes: Array<() => void>;
|
||||
createGameCalls: GameFixture[];
|
||||
applicationSubmitCalls: Array<{ gameId: string; raceName: string }>;
|
||||
inviteRedeemCalls: Array<{ gameId: string; inviteId: string }>;
|
||||
}
|
||||
|
||||
async function mockGateway(page: Page, initial: Partial<LobbyState> = {}): Promise<LobbyMocks> {
|
||||
const mocks: LobbyMocks = {
|
||||
state: {
|
||||
myGames: initial.myGames ?? [],
|
||||
publicGames: initial.publicGames ?? [],
|
||||
invitations: initial.invitations ?? [],
|
||||
applications: initial.applications ?? [],
|
||||
},
|
||||
pendingSubscribes: [],
|
||||
createGameCalls: [],
|
||||
applicationSubmitCalls: [],
|
||||
inviteRedeemCalls: [],
|
||||
};
|
||||
|
||||
await page.route("**/api/v1/public/auth/send-email-code", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ challenge_id: "ch-test-1" }),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route("**/api/v1/public/auth/confirm-email-code", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ device_session_id: "dev-test-1" }),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route("**/galaxy.gateway.v1.EdgeGateway/ExecuteCommand", async (route) => {
|
||||
const reqText = route.request().postData();
|
||||
if (reqText === null) {
|
||||
await route.fulfill({ status: 400 });
|
||||
return;
|
||||
}
|
||||
const req = fromJson(
|
||||
ExecuteCommandRequestSchema,
|
||||
JSON.parse(reqText) as JsonValue,
|
||||
);
|
||||
|
||||
let resultCode = "ok";
|
||||
let payload: Uint8Array;
|
||||
switch (req.messageType) {
|
||||
case "user.account.get":
|
||||
payload = buildAccountResponsePayload({
|
||||
userId: "user-1",
|
||||
email: "pilot@example.com",
|
||||
userName: "pilot",
|
||||
displayName: "Pilot",
|
||||
});
|
||||
break;
|
||||
case "lobby.my.games.list":
|
||||
payload = buildMyGamesListPayload(mocks.state.myGames);
|
||||
break;
|
||||
case "lobby.public.games.list":
|
||||
payload = buildPublicGamesListPayload(mocks.state.publicGames);
|
||||
break;
|
||||
case "lobby.my.invites.list":
|
||||
payload = buildMyInvitesListPayload(mocks.state.invitations);
|
||||
break;
|
||||
case "lobby.my.applications.list":
|
||||
payload = buildMyApplicationsListPayload(mocks.state.applications);
|
||||
break;
|
||||
case "lobby.game.create": {
|
||||
const decoded = GameCreateRequest.getRootAsGameCreateRequest(
|
||||
new ByteBuffer(req.payloadBytes),
|
||||
);
|
||||
const created: GameFixture = {
|
||||
gameId: "private-newly-created",
|
||||
gameName: decoded.gameName() ?? "",
|
||||
gameType: "private",
|
||||
status: "draft",
|
||||
ownerUserId: "user-1",
|
||||
minPlayers: decoded.minPlayers(),
|
||||
maxPlayers: decoded.maxPlayers(),
|
||||
enrollmentEndsAtMs: decoded.enrollmentEndsAtMs(),
|
||||
createdAtMs: BigInt(Date.now()),
|
||||
updatedAtMs: BigInt(Date.now()),
|
||||
};
|
||||
mocks.createGameCalls.push(created);
|
||||
mocks.state.myGames = [...mocks.state.myGames, created];
|
||||
payload = buildGameCreateResponsePayload(created);
|
||||
break;
|
||||
}
|
||||
case "lobby.application.submit": {
|
||||
const builder = req.payloadBytes;
|
||||
const submitReq = await import("../../src/proto/galaxy/fbs/lobby");
|
||||
const decoded = submitReq.ApplicationSubmitRequest.getRootAsApplicationSubmitRequest(
|
||||
new ByteBuffer(builder),
|
||||
);
|
||||
const application: ApplicationFixture = {
|
||||
applicationId: `app-${mocks.applicationSubmitCalls.length + 1}`,
|
||||
gameId: decoded.gameId() ?? "",
|
||||
applicantUserId: "user-1",
|
||||
raceName: decoded.raceName() ?? "",
|
||||
status: "pending",
|
||||
createdAtMs: BigInt(Date.now()),
|
||||
};
|
||||
mocks.applicationSubmitCalls.push({
|
||||
gameId: application.gameId,
|
||||
raceName: application.raceName,
|
||||
});
|
||||
mocks.state.applications = [application, ...mocks.state.applications];
|
||||
payload = buildApplicationSubmitResponsePayload(application);
|
||||
break;
|
||||
}
|
||||
case "lobby.invite.redeem": {
|
||||
const redeemMod = await import("../../src/proto/galaxy/fbs/lobby");
|
||||
const decoded = redeemMod.InviteRedeemRequest.getRootAsInviteRedeemRequest(
|
||||
new ByteBuffer(req.payloadBytes),
|
||||
);
|
||||
const gameId = decoded.gameId() ?? "";
|
||||
const inviteId = decoded.inviteId() ?? "";
|
||||
mocks.inviteRedeemCalls.push({ gameId, inviteId });
|
||||
const original = mocks.state.invitations.find((i) => i.inviteId === inviteId);
|
||||
const invite: InviteFixture = {
|
||||
...(original ?? {
|
||||
inviteId,
|
||||
gameId,
|
||||
inviterUserId: "user-host",
|
||||
invitedUserId: "user-1",
|
||||
raceName: "",
|
||||
}),
|
||||
status: "accepted",
|
||||
decidedAtMs: BigInt(Date.now()),
|
||||
};
|
||||
mocks.state.invitations = mocks.state.invitations.filter(
|
||||
(i) => i.inviteId !== inviteId,
|
||||
);
|
||||
const newGame: GameFixture = {
|
||||
gameId,
|
||||
gameName: "Invited Game",
|
||||
gameType: "private",
|
||||
status: "enrollment_open",
|
||||
ownerUserId: "user-host",
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
enrollmentEndsAtMs: BigInt(Date.now() + 1_000_000),
|
||||
};
|
||||
mocks.state.myGames = [...mocks.state.myGames, newGame];
|
||||
payload = buildInviteRedeemResponsePayload(invite);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
resultCode = "internal_error";
|
||||
payload = new Uint8Array();
|
||||
break;
|
||||
}
|
||||
|
||||
const responseJson = await forgeExecuteCommandResponseJson({
|
||||
requestId: req.requestId,
|
||||
timestampMs: BigInt(Date.now()),
|
||||
resultCode,
|
||||
payloadBytes: payload,
|
||||
});
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: responseJson,
|
||||
});
|
||||
});
|
||||
|
||||
await page.route(
|
||||
"**/galaxy.gateway.v1.EdgeGateway/SubscribeEvents",
|
||||
async (route) => {
|
||||
const action = await new Promise<"endOfStream" | "abort">((resolve) => {
|
||||
mocks.pendingSubscribes.push(() => resolve("endOfStream"));
|
||||
});
|
||||
if (action === "abort") {
|
||||
await route.abort();
|
||||
return;
|
||||
}
|
||||
const body = new TextEncoder().encode("{}");
|
||||
const frame = new Uint8Array(5 + body.length);
|
||||
frame[0] = 0x02;
|
||||
new DataView(frame.buffer).setUint32(1, body.length, false);
|
||||
frame.set(body, 5);
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/connect+json",
|
||||
body: Buffer.from(frame),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return mocks;
|
||||
}
|
||||
|
||||
async function completeLogin(page: Page): Promise<void> {
|
||||
await page.goto("/");
|
||||
await expect(page).toHaveURL(/\/login$/);
|
||||
// The login page renders the inputs `readonly` as a Safari
|
||||
// autofill-suppression workaround; the readonly attribute is
|
||||
// dropped on first focus. Playwright's `fill()` checks editability
|
||||
// before its own focus call, so emulate the user gesture explicitly:
|
||||
// click the input (focus → readonly drops), then fill.
|
||||
await page.getByTestId("login-email-input").click();
|
||||
await page.getByTestId("login-email-input").fill("pilot@example.com");
|
||||
await page.getByTestId("login-email-submit").click();
|
||||
await expect(page.getByTestId("login-code-input")).toBeVisible();
|
||||
await page.getByTestId("login-code-input").click();
|
||||
await page.getByTestId("login-code-input").fill("123456");
|
||||
await page.getByTestId("login-code-submit").click();
|
||||
await expect(page).toHaveURL(/\/lobby$/);
|
||||
}
|
||||
|
||||
test.describe("Phase 8 — lobby flow", () => {
|
||||
test("create-game flow lands the new game in My Games", async ({ page }) => {
|
||||
const mocks = await mockGateway(page);
|
||||
await completeLogin(page);
|
||||
|
||||
await expect(page.getByTestId("lobby-my-games-empty")).toBeVisible();
|
||||
await expect(page.getByTestId("lobby-public-games-empty")).toBeVisible();
|
||||
|
||||
await page.getByTestId("lobby-create-button").click();
|
||||
await expect(page).toHaveURL(/\/lobby\/create$/);
|
||||
|
||||
await page.getByTestId("lobby-create-game-name").click();
|
||||
await page.getByTestId("lobby-create-game-name").fill("First Contact");
|
||||
await page.getByTestId("lobby-create-turn-schedule").click();
|
||||
await page.getByTestId("lobby-create-turn-schedule").fill("0 0 * * *");
|
||||
await page
|
||||
.getByTestId("lobby-create-enrollment-ends-at")
|
||||
.fill("2026-06-01T12:00");
|
||||
await page.getByTestId("lobby-create-submit").click();
|
||||
|
||||
await expect(page).toHaveURL(/\/lobby$/);
|
||||
await expect(page.getByTestId("lobby-my-game-card")).toContainText("First Contact");
|
||||
expect(mocks.createGameCalls.length).toBe(1);
|
||||
expect(mocks.createGameCalls[0]!.gameName).toBe("First Contact");
|
||||
|
||||
mocks.pendingSubscribes.forEach((resolve) => resolve());
|
||||
});
|
||||
|
||||
test("submitting an application produces a pending applications card", async ({
|
||||
page,
|
||||
}) => {
|
||||
const mocks = await mockGateway(page, {
|
||||
publicGames: [
|
||||
{
|
||||
gameId: "public-1",
|
||||
gameName: "Open Lobby",
|
||||
gameType: "public",
|
||||
status: "enrollment_open",
|
||||
},
|
||||
],
|
||||
});
|
||||
await completeLogin(page);
|
||||
|
||||
await expect(page.getByTestId("lobby-public-game-apply")).toBeVisible();
|
||||
await page.getByTestId("lobby-public-game-apply").click();
|
||||
await page
|
||||
.getByTestId("lobby-application-race-name")
|
||||
.fill("Vegan Federation");
|
||||
await page.getByTestId("lobby-application-submit").click();
|
||||
|
||||
await expect(page.getByTestId("lobby-application-card")).toBeVisible();
|
||||
expect(mocks.applicationSubmitCalls).toEqual([
|
||||
{ gameId: "public-1", raceName: "Vegan Federation" },
|
||||
]);
|
||||
|
||||
mocks.pendingSubscribes.forEach((resolve) => resolve());
|
||||
});
|
||||
|
||||
test("accepting an invitation removes it and adds the game to My Games", async ({
|
||||
page,
|
||||
}) => {
|
||||
const mocks = await mockGateway(page, {
|
||||
invitations: [
|
||||
{
|
||||
inviteId: "invite-1",
|
||||
gameId: "private-1",
|
||||
inviterUserId: "user-host",
|
||||
invitedUserId: "user-1",
|
||||
raceName: "Vegan Federation",
|
||||
status: "pending",
|
||||
},
|
||||
],
|
||||
});
|
||||
await completeLogin(page);
|
||||
|
||||
await expect(page.getByTestId("lobby-invite-accept")).toBeVisible();
|
||||
await page.getByTestId("lobby-invite-accept").click();
|
||||
|
||||
await expect(page.getByTestId("lobby-invite-accept")).toBeHidden();
|
||||
await expect(page.getByTestId("lobby-my-game-card")).toContainText("Invited Game");
|
||||
expect(mocks.inviteRedeemCalls).toEqual([
|
||||
{ gameId: "private-1", inviteId: "invite-1" },
|
||||
]);
|
||||
|
||||
mocks.pendingSubscribes.forEach((resolve) => resolve());
|
||||
});
|
||||
});
|
||||
@@ -83,7 +83,8 @@ describe("GalaxyClient.executeCommand", () => {
|
||||
new TextEncoder().encode("client-payload"),
|
||||
);
|
||||
|
||||
expect(Array.from(out)).toEqual(Array.from(responsePayload));
|
||||
expect(out.resultCode).toBe("ok");
|
||||
expect(Array.from(out.payloadBytes)).toEqual(Array.from(responsePayload));
|
||||
expect(signer).toHaveBeenCalledWith(canonicalBytes);
|
||||
expect(sha256).toHaveBeenCalledTimes(1);
|
||||
expect(core.signRequest).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
// Unit tests for the typed lobby.ts wrappers. They invoke the
|
||||
// wrappers against a minimal stub of `GalaxyClient.executeCommand`
|
||||
// that captures the message type and FlatBuffers request payload,
|
||||
// then returns a forged FlatBuffers response payload built with the
|
||||
// generated TS bindings. No network, no signing — the test confirms
|
||||
// the encoder/decoder shape matches the gateway contract and that
|
||||
// non-`ok` result codes are surfaced as a `LobbyError`.
|
||||
|
||||
import { Builder, ByteBuffer } from "flatbuffers";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
LobbyError,
|
||||
createGame,
|
||||
declineInvite,
|
||||
listMyApplications,
|
||||
listMyGames,
|
||||
listMyInvites,
|
||||
listPublicGames,
|
||||
redeemInvite,
|
||||
submitApplication,
|
||||
} from "../src/api/lobby";
|
||||
import {
|
||||
ApplicationSubmitResponse,
|
||||
ApplicationSummary,
|
||||
ErrorBody,
|
||||
ErrorResponse,
|
||||
GameCreateResponse,
|
||||
GameSummary,
|
||||
InviteDeclineResponse,
|
||||
InviteRedeemResponse,
|
||||
InviteSummary,
|
||||
MyApplicationsListResponse,
|
||||
MyGamesListResponse,
|
||||
MyInvitesListResponse,
|
||||
PublicGamesListResponse,
|
||||
} from "../src/proto/galaxy/fbs/lobby";
|
||||
import type { GalaxyClient } from "../src/api/galaxy-client";
|
||||
import {
|
||||
GameCreateRequest,
|
||||
PublicGamesListRequest,
|
||||
ApplicationSubmitRequest,
|
||||
InviteRedeemRequest,
|
||||
InviteDeclineRequest,
|
||||
} from "../src/proto/galaxy/fbs/lobby";
|
||||
|
||||
interface Captured {
|
||||
messageType: string;
|
||||
payload: Uint8Array;
|
||||
}
|
||||
|
||||
function makeStub(
|
||||
respondWith: (c: Captured) => { resultCode?: string; payloadBytes: Uint8Array },
|
||||
): {
|
||||
client: GalaxyClient;
|
||||
captured: Captured[];
|
||||
} {
|
||||
const captured: Captured[] = [];
|
||||
const stub = {
|
||||
executeCommand: vi.fn(async (messageType: string, payload: Uint8Array) => {
|
||||
const c = { messageType, payload };
|
||||
captured.push(c);
|
||||
const result = respondWith(c);
|
||||
return {
|
||||
resultCode: result.resultCode ?? "ok",
|
||||
payloadBytes: result.payloadBytes,
|
||||
};
|
||||
}),
|
||||
} as unknown as GalaxyClient;
|
||||
return { client: stub, captured };
|
||||
}
|
||||
|
||||
function encodeGameSummary(builder: Builder): number {
|
||||
const gameId = builder.createString("g-1");
|
||||
const gameName = builder.createString("Test Game");
|
||||
const gameType = builder.createString("private");
|
||||
const status = builder.createString("draft");
|
||||
const ownerUserId = builder.createString("user-1");
|
||||
GameSummary.startGameSummary(builder);
|
||||
GameSummary.addGameId(builder, gameId);
|
||||
GameSummary.addGameName(builder, gameName);
|
||||
GameSummary.addGameType(builder, gameType);
|
||||
GameSummary.addStatus(builder, status);
|
||||
GameSummary.addOwnerUserId(builder, ownerUserId);
|
||||
GameSummary.addMinPlayers(builder, 2);
|
||||
GameSummary.addMaxPlayers(builder, 8);
|
||||
GameSummary.addEnrollmentEndsAtMs(builder, 1_780_000_000_000n);
|
||||
GameSummary.addCreatedAtMs(builder, 1_770_000_000_000n);
|
||||
GameSummary.addUpdatedAtMs(builder, 1_770_000_000_000n);
|
||||
return GameSummary.endGameSummary(builder);
|
||||
}
|
||||
|
||||
function encodeApplicationSummary(builder: Builder, status: string): number {
|
||||
const applicationId = builder.createString("app-1");
|
||||
const gameId = builder.createString("g-1");
|
||||
const applicantUserId = builder.createString("user-1");
|
||||
const raceName = builder.createString("Vegan Federation");
|
||||
const statusOff = builder.createString(status);
|
||||
ApplicationSummary.startApplicationSummary(builder);
|
||||
ApplicationSummary.addApplicationId(builder, applicationId);
|
||||
ApplicationSummary.addGameId(builder, gameId);
|
||||
ApplicationSummary.addApplicantUserId(builder, applicantUserId);
|
||||
ApplicationSummary.addRaceName(builder, raceName);
|
||||
ApplicationSummary.addStatus(builder, statusOff);
|
||||
ApplicationSummary.addCreatedAtMs(builder, 1_770_000_000_000n);
|
||||
ApplicationSummary.addDecidedAtMs(builder, status === "pending" ? 0n : 1_770_010_000_000n);
|
||||
return ApplicationSummary.endApplicationSummary(builder);
|
||||
}
|
||||
|
||||
function encodeInviteSummary(builder: Builder, status: string): number {
|
||||
const inviteId = builder.createString("invite-1");
|
||||
const gameId = builder.createString("g-1");
|
||||
const inviter = builder.createString("user-host");
|
||||
const invited = builder.createString("user-1");
|
||||
const code = builder.createString("");
|
||||
const race = builder.createString("Vegan Federation");
|
||||
const statusOff = builder.createString(status);
|
||||
InviteSummary.startInviteSummary(builder);
|
||||
InviteSummary.addInviteId(builder, inviteId);
|
||||
InviteSummary.addGameId(builder, gameId);
|
||||
InviteSummary.addInviterUserId(builder, inviter);
|
||||
InviteSummary.addInvitedUserId(builder, invited);
|
||||
InviteSummary.addCode(builder, code);
|
||||
InviteSummary.addRaceName(builder, race);
|
||||
InviteSummary.addStatus(builder, statusOff);
|
||||
InviteSummary.addCreatedAtMs(builder, 1_770_000_000_000n);
|
||||
InviteSummary.addExpiresAtMs(builder, 1_780_000_000_000n);
|
||||
InviteSummary.addDecidedAtMs(builder, status === "pending" ? 0n : 1_770_010_000_000n);
|
||||
return InviteSummary.endInviteSummary(builder);
|
||||
}
|
||||
|
||||
describe("lobby.ts wrappers", () => {
|
||||
test("listMyGames decodes the response and reports the message type", async () => {
|
||||
const { client, captured } = makeStub(() => {
|
||||
const builder = new Builder(256);
|
||||
const item = encodeGameSummary(builder);
|
||||
const items = MyGamesListResponse.createItemsVector(builder, [item]);
|
||||
MyGamesListResponse.startMyGamesListResponse(builder);
|
||||
MyGamesListResponse.addItems(builder, items);
|
||||
builder.finish(MyGamesListResponse.endMyGamesListResponse(builder));
|
||||
return { payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
|
||||
const games = await listMyGames(client);
|
||||
expect(captured[0]!.messageType).toBe("lobby.my.games.list");
|
||||
expect(games.length).toBe(1);
|
||||
expect(games[0]!.gameId).toBe("g-1");
|
||||
expect(games[0]!.minPlayers).toBe(2);
|
||||
});
|
||||
|
||||
test("listPublicGames passes pagination and decodes pageSize/total", async () => {
|
||||
const { client, captured } = makeStub(() => {
|
||||
const builder = new Builder(256);
|
||||
const item = encodeGameSummary(builder);
|
||||
const items = PublicGamesListResponse.createItemsVector(builder, [item]);
|
||||
PublicGamesListResponse.startPublicGamesListResponse(builder);
|
||||
PublicGamesListResponse.addItems(builder, items);
|
||||
PublicGamesListResponse.addPage(builder, 2);
|
||||
PublicGamesListResponse.addPageSize(builder, 25);
|
||||
PublicGamesListResponse.addTotal(builder, 51);
|
||||
builder.finish(PublicGamesListResponse.endPublicGamesListResponse(builder));
|
||||
return { payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
|
||||
const page = await listPublicGames(client, { page: 2, pageSize: 25 });
|
||||
expect(captured[0]!.messageType).toBe("lobby.public.games.list");
|
||||
const decodedRequest = PublicGamesListRequest.getRootAsPublicGamesListRequest(
|
||||
new ByteBuffer(captured[0]!.payload),
|
||||
);
|
||||
expect(decodedRequest.page()).toBe(2);
|
||||
expect(decodedRequest.pageSize()).toBe(25);
|
||||
|
||||
expect(page.items.length).toBe(1);
|
||||
expect(page.page).toBe(2);
|
||||
expect(page.pageSize).toBe(25);
|
||||
expect(page.total).toBe(51);
|
||||
});
|
||||
|
||||
test("listMyApplications decodes pending and decided records", async () => {
|
||||
const { client } = makeStub(() => {
|
||||
const builder = new Builder(256);
|
||||
const pending = encodeApplicationSummary(builder, "pending");
|
||||
const approved = encodeApplicationSummary(builder, "approved");
|
||||
const items = MyApplicationsListResponse.createItemsVector(builder, [pending, approved]);
|
||||
MyApplicationsListResponse.startMyApplicationsListResponse(builder);
|
||||
MyApplicationsListResponse.addItems(builder, items);
|
||||
builder.finish(MyApplicationsListResponse.endMyApplicationsListResponse(builder));
|
||||
return { payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
|
||||
const applications = await listMyApplications(client);
|
||||
expect(applications.length).toBe(2);
|
||||
expect(applications[0]!.status).toBe("pending");
|
||||
expect(applications[0]!.decidedAt).toBeNull();
|
||||
expect(applications[1]!.status).toBe("approved");
|
||||
expect(applications[1]!.decidedAt).not.toBeNull();
|
||||
});
|
||||
|
||||
test("listMyInvites decodes user-bound invites", async () => {
|
||||
const { client } = makeStub(() => {
|
||||
const builder = new Builder(256);
|
||||
const invite = encodeInviteSummary(builder, "pending");
|
||||
const items = MyInvitesListResponse.createItemsVector(builder, [invite]);
|
||||
MyInvitesListResponse.startMyInvitesListResponse(builder);
|
||||
MyInvitesListResponse.addItems(builder, items);
|
||||
builder.finish(MyInvitesListResponse.endMyInvitesListResponse(builder));
|
||||
return { payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
|
||||
const invites = await listMyInvites(client);
|
||||
expect(invites.length).toBe(1);
|
||||
expect(invites[0]!.invitedUserId).toBe("user-1");
|
||||
expect(invites[0]!.status).toBe("pending");
|
||||
expect(invites[0]!.decidedAt).toBeNull();
|
||||
});
|
||||
|
||||
test("createGame encodes every field and decodes the returned summary", async () => {
|
||||
const { client, captured } = makeStub(() => {
|
||||
const builder = new Builder(256);
|
||||
const game = encodeGameSummary(builder);
|
||||
GameCreateResponse.startGameCreateResponse(builder);
|
||||
GameCreateResponse.addGame(builder, game);
|
||||
builder.finish(GameCreateResponse.endGameCreateResponse(builder));
|
||||
return { payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
|
||||
const enrollment = new Date(1_780_000_000_000);
|
||||
const result = await createGame(client, {
|
||||
gameName: "First Contact",
|
||||
description: "",
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
startGapHours: 24,
|
||||
startGapPlayers: 2,
|
||||
enrollmentEndsAt: enrollment,
|
||||
turnSchedule: "0 0 * * *",
|
||||
targetEngineVersion: "v1",
|
||||
});
|
||||
|
||||
expect(captured[0]!.messageType).toBe("lobby.game.create");
|
||||
const request = GameCreateRequest.getRootAsGameCreateRequest(
|
||||
new ByteBuffer(captured[0]!.payload),
|
||||
);
|
||||
expect(request.gameName()).toBe("First Contact");
|
||||
expect(request.turnSchedule()).toBe("0 0 * * *");
|
||||
expect(request.targetEngineVersion()).toBe("v1");
|
||||
expect(request.minPlayers()).toBe(2);
|
||||
expect(request.maxPlayers()).toBe(8);
|
||||
expect(request.enrollmentEndsAtMs()).toBe(BigInt(enrollment.getTime()));
|
||||
|
||||
expect(result.gameId).toBe("g-1");
|
||||
});
|
||||
|
||||
test("submitApplication encodes game_id and race_name", async () => {
|
||||
const { client, captured } = makeStub(() => {
|
||||
const builder = new Builder(128);
|
||||
const app = encodeApplicationSummary(builder, "pending");
|
||||
ApplicationSubmitResponse.startApplicationSubmitResponse(builder);
|
||||
ApplicationSubmitResponse.addApplication(builder, app);
|
||||
builder.finish(ApplicationSubmitResponse.endApplicationSubmitResponse(builder));
|
||||
return { payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
|
||||
const submitted = await submitApplication(client, "public-1", "Vegan Federation");
|
||||
expect(captured[0]!.messageType).toBe("lobby.application.submit");
|
||||
const decoded = ApplicationSubmitRequest.getRootAsApplicationSubmitRequest(
|
||||
new ByteBuffer(captured[0]!.payload),
|
||||
);
|
||||
expect(decoded.gameId()).toBe("public-1");
|
||||
expect(decoded.raceName()).toBe("Vegan Federation");
|
||||
expect(submitted.applicationId).toBe("app-1");
|
||||
});
|
||||
|
||||
test("redeemInvite and declineInvite hit their respective message types", async () => {
|
||||
const stubRedeem = makeStub(() => {
|
||||
const builder = new Builder(128);
|
||||
const invite = encodeInviteSummary(builder, "accepted");
|
||||
InviteRedeemResponse.startInviteRedeemResponse(builder);
|
||||
InviteRedeemResponse.addInvite(builder, invite);
|
||||
builder.finish(InviteRedeemResponse.endInviteRedeemResponse(builder));
|
||||
return { payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
const redeemed = await redeemInvite(stubRedeem.client, "private-1", "invite-1");
|
||||
expect(stubRedeem.captured[0]!.messageType).toBe("lobby.invite.redeem");
|
||||
const redeemReq = InviteRedeemRequest.getRootAsInviteRedeemRequest(
|
||||
new ByteBuffer(stubRedeem.captured[0]!.payload),
|
||||
);
|
||||
expect(redeemReq.gameId()).toBe("private-1");
|
||||
expect(redeemReq.inviteId()).toBe("invite-1");
|
||||
expect(redeemed.status).toBe("accepted");
|
||||
|
||||
const stubDecline = makeStub(() => {
|
||||
const builder = new Builder(128);
|
||||
const invite = encodeInviteSummary(builder, "declined");
|
||||
InviteDeclineResponse.startInviteDeclineResponse(builder);
|
||||
InviteDeclineResponse.addInvite(builder, invite);
|
||||
builder.finish(InviteDeclineResponse.endInviteDeclineResponse(builder));
|
||||
return { payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
const declined = await declineInvite(stubDecline.client, "private-1", "invite-1");
|
||||
expect(stubDecline.captured[0]!.messageType).toBe("lobby.invite.decline");
|
||||
const declineReq = InviteDeclineRequest.getRootAsInviteDeclineRequest(
|
||||
new ByteBuffer(stubDecline.captured[0]!.payload),
|
||||
);
|
||||
expect(declineReq.gameId()).toBe("private-1");
|
||||
expect(declineReq.inviteId()).toBe("invite-1");
|
||||
expect(declined.status).toBe("declined");
|
||||
});
|
||||
|
||||
test("non-ok result codes are surfaced as a LobbyError with code and message", async () => {
|
||||
const { client } = makeStub(() => {
|
||||
const builder = new Builder(128);
|
||||
const code = builder.createString("conflict");
|
||||
const message = builder.createString("game is not in enrollment_open");
|
||||
ErrorBody.startErrorBody(builder);
|
||||
ErrorBody.addCode(builder, code);
|
||||
ErrorBody.addMessage(builder, message);
|
||||
const errorOff = ErrorBody.endErrorBody(builder);
|
||||
ErrorResponse.startErrorResponse(builder);
|
||||
ErrorResponse.addError(builder, errorOff);
|
||||
builder.finish(ErrorResponse.endErrorResponse(builder));
|
||||
return { resultCode: "conflict", payloadBytes: builder.asUint8Array() };
|
||||
});
|
||||
|
||||
await expect(submitApplication(client, "public-1", "race")).rejects.toThrow(LobbyError);
|
||||
try {
|
||||
await submitApplication(client, "public-1", "race");
|
||||
} catch (err) {
|
||||
const lobbyError = err as LobbyError;
|
||||
expect(lobbyError.code).toBe("conflict");
|
||||
expect(lobbyError.message).toBe("game is not in enrollment_open");
|
||||
expect(lobbyError.resultCode).toBe("conflict");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
// Component tests for the create-game form. The lobby API is mocked
|
||||
// at module level; the GalaxyClient is replaced with a stub that does
|
||||
// nothing (the test only asserts the createGame wrapper is invoked
|
||||
// with the right shape).
|
||||
|
||||
import "fake-indexeddb/auto";
|
||||
import { fireEvent, render, waitFor } from "@testing-library/svelte";
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import type { IDBPDatabase } from "idb";
|
||||
|
||||
import { i18n } from "../src/lib/i18n/index.svelte";
|
||||
import { session } from "../src/lib/session-store.svelte";
|
||||
import { type GalaxyDB, openGalaxyDB } from "../src/platform/store/idb";
|
||||
import { IDBCache } from "../src/platform/store/idb-cache";
|
||||
import { WebCryptoKeyStore } from "../src/platform/store/webcrypto-keystore";
|
||||
|
||||
const gotoSpy = vi.fn<(url: string) => Promise<void>>(async () => {});
|
||||
vi.mock("$app/navigation", () => ({
|
||||
goto: (url: string) => gotoSpy(url),
|
||||
}));
|
||||
|
||||
const createGameSpy = vi.fn();
|
||||
vi.mock("../src/api/lobby", async () => {
|
||||
const actual = await vi.importActual<typeof import("../src/api/lobby")>(
|
||||
"../src/api/lobby",
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
createGame: (...args: unknown[]) => createGameSpy(...args),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../src/lib/env", () => ({
|
||||
GATEWAY_BASE_URL: "http://gateway.test",
|
||||
GATEWAY_RESPONSE_PUBLIC_KEY: new Uint8Array(32).fill(0x55),
|
||||
}));
|
||||
|
||||
vi.mock("../src/api/connect", () => ({
|
||||
createEdgeGatewayClient: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
vi.mock("../src/api/galaxy-client", () => {
|
||||
class FakeGalaxyClient {
|
||||
executeCommand = vi.fn(async () => ({
|
||||
resultCode: "ok",
|
||||
payloadBytes: new Uint8Array(),
|
||||
}));
|
||||
}
|
||||
return { GalaxyClient: FakeGalaxyClient };
|
||||
});
|
||||
|
||||
vi.mock("../src/platform/core/index", () => ({
|
||||
loadCore: async () => ({
|
||||
signRequest: () => new Uint8Array(),
|
||||
verifyResponse: () => true,
|
||||
verifyEvent: () => true,
|
||||
verifyPayloadHash: () => true,
|
||||
}),
|
||||
}));
|
||||
|
||||
let db: IDBPDatabase<GalaxyDB>;
|
||||
let dbName: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbName = `galaxy-ui-test-${crypto.randomUUID()}`;
|
||||
db = await openGalaxyDB(dbName);
|
||||
const store = {
|
||||
keyStore: new WebCryptoKeyStore(db),
|
||||
cache: new IDBCache(db),
|
||||
};
|
||||
session.resetForTests();
|
||||
session.setStoreLoaderForTests(async () => store);
|
||||
await session.init();
|
||||
await session.signIn("device-1");
|
||||
i18n.resetForTests("en");
|
||||
createGameSpy.mockReset();
|
||||
gotoSpy.mockReset();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
session.resetForTests();
|
||||
i18n.resetForTests("en");
|
||||
db.close();
|
||||
await new Promise<void>((resolve) => {
|
||||
const req = indexedDB.deleteDatabase(dbName);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => resolve();
|
||||
req.onblocked = () => resolve();
|
||||
});
|
||||
});
|
||||
|
||||
async function importCreatePage(): Promise<typeof import("../src/routes/lobby/create/+page.svelte")> {
|
||||
return import("../src/routes/lobby/create/+page.svelte");
|
||||
}
|
||||
|
||||
describe("lobby/create page", () => {
|
||||
test("submitting a valid form invokes createGame with the entered values and navigates back", async () => {
|
||||
createGameSpy.mockResolvedValue({
|
||||
gameId: "private-new",
|
||||
gameName: "First Contact",
|
||||
gameType: "private",
|
||||
status: "draft",
|
||||
ownerUserId: "user-1",
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
enrollmentEndsAt: new Date(),
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
|
||||
const Page = (await importCreatePage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("lobby-create-form")).toBeInTheDocument(),
|
||||
);
|
||||
|
||||
await fireEvent.input(ui.getByTestId("lobby-create-game-name"), {
|
||||
target: { value: "First Contact" },
|
||||
});
|
||||
await fireEvent.input(ui.getByTestId("lobby-create-description"), {
|
||||
target: { value: "" },
|
||||
});
|
||||
await fireEvent.input(ui.getByTestId("lobby-create-turn-schedule"), {
|
||||
target: { value: "0 0 * * *" },
|
||||
});
|
||||
await fireEvent.input(ui.getByTestId("lobby-create-enrollment-ends-at"), {
|
||||
target: { value: "2026-06-01T12:00" },
|
||||
});
|
||||
|
||||
await fireEvent.click(ui.getByTestId("lobby-create-submit"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createGameSpy).toHaveBeenCalledTimes(1);
|
||||
const call = createGameSpy.mock.calls[0]!;
|
||||
const input = call[1] as Record<string, unknown>;
|
||||
expect(input.gameName).toBe("First Contact");
|
||||
expect(input.turnSchedule).toBe("0 0 * * *");
|
||||
expect(input.minPlayers).toBe(2);
|
||||
expect(input.maxPlayers).toBe(8);
|
||||
expect(input.startGapHours).toBe(24);
|
||||
expect(input.startGapPlayers).toBe(2);
|
||||
expect(input.targetEngineVersion).toBe("v1");
|
||||
expect(input.enrollmentEndsAt).toBeInstanceOf(Date);
|
||||
expect(gotoSpy).toHaveBeenCalledWith("/lobby");
|
||||
});
|
||||
});
|
||||
|
||||
test("submitting with an empty game name surfaces a validation error and does not call the API", async () => {
|
||||
const Page = (await importCreatePage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("lobby-create-form")).toBeInTheDocument(),
|
||||
);
|
||||
|
||||
// turn_schedule starts populated with the default; clear game_name to trigger the error
|
||||
await fireEvent.input(ui.getByTestId("lobby-create-game-name"), {
|
||||
target: { value: " " },
|
||||
});
|
||||
await fireEvent.input(ui.getByTestId("lobby-create-enrollment-ends-at"), {
|
||||
target: { value: "2026-06-01T12:00" },
|
||||
});
|
||||
await fireEvent.click(ui.getByTestId("lobby-create-submit"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(ui.getByTestId("lobby-create-error")).toHaveTextContent(
|
||||
"game name must not be empty",
|
||||
);
|
||||
expect(createGameSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test("cancel button navigates back to /lobby without calling the API", async () => {
|
||||
const Page = (await importCreatePage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("lobby-create-cancel")).toBeInTheDocument(),
|
||||
);
|
||||
await fireEvent.click(ui.getByTestId("lobby-create-cancel"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(gotoSpy).toHaveBeenCalledWith("/lobby");
|
||||
expect(createGameSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,494 @@
|
||||
// Round-trip tests for the generated TS FlatBuffers bindings under
|
||||
// `src/proto/galaxy/fbs/lobby/`. These guard against codegen drift —
|
||||
// if the wire schema and the bindings disagree, the round-trip fails
|
||||
// instead of letting a broken binding ship silently.
|
||||
|
||||
import { Builder, ByteBuffer } from "flatbuffers";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
ApplicationSubmitRequest,
|
||||
ApplicationSubmitResponse,
|
||||
ApplicationSummary,
|
||||
ErrorBody,
|
||||
ErrorResponse,
|
||||
GameCreateRequest,
|
||||
GameCreateResponse,
|
||||
GameSummary,
|
||||
InviteDeclineRequest,
|
||||
InviteDeclineResponse,
|
||||
InviteRedeemRequest,
|
||||
InviteRedeemResponse,
|
||||
InviteSummary,
|
||||
MyApplicationsListRequest,
|
||||
MyApplicationsListResponse,
|
||||
MyGamesListRequest,
|
||||
MyGamesListResponse,
|
||||
MyInvitesListRequest,
|
||||
MyInvitesListResponse,
|
||||
OpenEnrollmentRequest,
|
||||
OpenEnrollmentResponse,
|
||||
PublicGamesListRequest,
|
||||
PublicGamesListResponse,
|
||||
} from "../src/proto/galaxy/fbs/lobby";
|
||||
|
||||
interface GameSummaryFixture {
|
||||
gameId: string;
|
||||
gameName: string;
|
||||
gameType: string;
|
||||
status: string;
|
||||
ownerUserId: string;
|
||||
minPlayers: number;
|
||||
maxPlayers: number;
|
||||
enrollmentEndsAtMs: bigint;
|
||||
createdAtMs: bigint;
|
||||
updatedAtMs: bigint;
|
||||
}
|
||||
|
||||
const PRIVATE_GAME: GameSummaryFixture = {
|
||||
gameId: "game-private-7c8f",
|
||||
gameName: "First Contact",
|
||||
gameType: "private",
|
||||
status: "draft",
|
||||
ownerUserId: "user-9912",
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
enrollmentEndsAtMs: 1_780_000_000_000n,
|
||||
createdAtMs: 1_770_000_000_000n,
|
||||
updatedAtMs: 1_770_000_300_000n,
|
||||
};
|
||||
|
||||
const PUBLIC_GAME: GameSummaryFixture = {
|
||||
gameId: "game-public-aabb",
|
||||
gameName: "Open Lobby",
|
||||
gameType: "public",
|
||||
status: "enrollment_open",
|
||||
ownerUserId: "",
|
||||
minPlayers: 4,
|
||||
maxPlayers: 12,
|
||||
enrollmentEndsAtMs: 1_780_500_000_000n,
|
||||
createdAtMs: 1_770_500_000_000n,
|
||||
updatedAtMs: 1_770_600_000_000n,
|
||||
};
|
||||
|
||||
function encodeGameSummary(builder: Builder, value: GameSummaryFixture): number {
|
||||
const gameId = builder.createString(value.gameId);
|
||||
const gameName = builder.createString(value.gameName);
|
||||
const gameType = builder.createString(value.gameType);
|
||||
const status = builder.createString(value.status);
|
||||
const ownerUserId = builder.createString(value.ownerUserId);
|
||||
GameSummary.startGameSummary(builder);
|
||||
GameSummary.addGameId(builder, gameId);
|
||||
GameSummary.addGameName(builder, gameName);
|
||||
GameSummary.addGameType(builder, gameType);
|
||||
GameSummary.addStatus(builder, status);
|
||||
GameSummary.addOwnerUserId(builder, ownerUserId);
|
||||
GameSummary.addMinPlayers(builder, value.minPlayers);
|
||||
GameSummary.addMaxPlayers(builder, value.maxPlayers);
|
||||
GameSummary.addEnrollmentEndsAtMs(builder, value.enrollmentEndsAtMs);
|
||||
GameSummary.addCreatedAtMs(builder, value.createdAtMs);
|
||||
GameSummary.addUpdatedAtMs(builder, value.updatedAtMs);
|
||||
return GameSummary.endGameSummary(builder);
|
||||
}
|
||||
|
||||
function expectGameSummary(actual: GameSummary | null, want: GameSummaryFixture): void {
|
||||
expect(actual).not.toBeNull();
|
||||
const got = actual!;
|
||||
expect(got.gameId()).toBe(want.gameId);
|
||||
expect(got.gameName()).toBe(want.gameName);
|
||||
expect(got.gameType()).toBe(want.gameType);
|
||||
expect(got.status()).toBe(want.status);
|
||||
expect(got.ownerUserId()).toBe(want.ownerUserId);
|
||||
expect(got.minPlayers()).toBe(want.minPlayers);
|
||||
expect(got.maxPlayers()).toBe(want.maxPlayers);
|
||||
expect(got.enrollmentEndsAtMs()).toBe(want.enrollmentEndsAtMs);
|
||||
expect(got.createdAtMs()).toBe(want.createdAtMs);
|
||||
expect(got.updatedAtMs()).toBe(want.updatedAtMs);
|
||||
}
|
||||
|
||||
describe("lobby FlatBuffers TS bindings", () => {
|
||||
test("MyGamesListRequest round-trips an empty body", () => {
|
||||
const builder = new Builder(32);
|
||||
MyGamesListRequest.startMyGamesListRequest(builder);
|
||||
builder.finish(MyGamesListRequest.endMyGamesListRequest(builder));
|
||||
const bytes = builder.asUint8Array();
|
||||
const decoded = MyGamesListRequest.getRootAsMyGamesListRequest(new ByteBuffer(bytes));
|
||||
expect(decoded).toBeDefined();
|
||||
});
|
||||
|
||||
test("MyGamesListResponse encodes and decodes multiple summaries", () => {
|
||||
const builder = new Builder(512);
|
||||
const item0 = encodeGameSummary(builder, PRIVATE_GAME);
|
||||
const item1 = encodeGameSummary(builder, PUBLIC_GAME);
|
||||
const items = MyGamesListResponse.createItemsVector(builder, [item0, item1]);
|
||||
MyGamesListResponse.startMyGamesListResponse(builder);
|
||||
MyGamesListResponse.addItems(builder, items);
|
||||
builder.finish(MyGamesListResponse.endMyGamesListResponse(builder));
|
||||
|
||||
const bytes = builder.asUint8Array();
|
||||
const decoded = MyGamesListResponse.getRootAsMyGamesListResponse(new ByteBuffer(bytes));
|
||||
expect(decoded.itemsLength()).toBe(2);
|
||||
expectGameSummary(decoded.items(0), PRIVATE_GAME);
|
||||
expectGameSummary(decoded.items(1), PUBLIC_GAME);
|
||||
});
|
||||
|
||||
test("PublicGamesListResponse preserves pagination metadata", () => {
|
||||
const builder = new Builder(256);
|
||||
const item = encodeGameSummary(builder, PUBLIC_GAME);
|
||||
const items = PublicGamesListResponse.createItemsVector(builder, [item]);
|
||||
PublicGamesListResponse.startPublicGamesListResponse(builder);
|
||||
PublicGamesListResponse.addItems(builder, items);
|
||||
PublicGamesListResponse.addPage(builder, 3);
|
||||
PublicGamesListResponse.addPageSize(builder, 25);
|
||||
PublicGamesListResponse.addTotal(builder, 51);
|
||||
builder.finish(PublicGamesListResponse.endPublicGamesListResponse(builder));
|
||||
const bytes = builder.asUint8Array();
|
||||
const decoded = PublicGamesListResponse.getRootAsPublicGamesListResponse(
|
||||
new ByteBuffer(bytes),
|
||||
);
|
||||
expect(decoded.itemsLength()).toBe(1);
|
||||
expectGameSummary(decoded.items(0), PUBLIC_GAME);
|
||||
expect(decoded.page()).toBe(3);
|
||||
expect(decoded.pageSize()).toBe(25);
|
||||
expect(decoded.total()).toBe(51);
|
||||
});
|
||||
|
||||
test("PublicGamesListRequest round-trips page numbers", () => {
|
||||
const builder = new Builder(32);
|
||||
PublicGamesListRequest.startPublicGamesListRequest(builder);
|
||||
PublicGamesListRequest.addPage(builder, 2);
|
||||
PublicGamesListRequest.addPageSize(builder, 10);
|
||||
builder.finish(PublicGamesListRequest.endPublicGamesListRequest(builder));
|
||||
const decoded = PublicGamesListRequest.getRootAsPublicGamesListRequest(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded.page()).toBe(2);
|
||||
expect(decoded.pageSize()).toBe(10);
|
||||
});
|
||||
|
||||
test("ApplicationSummary preserves pending and decided records", () => {
|
||||
const builder = new Builder(256);
|
||||
|
||||
const pendingId = builder.createString("app-1");
|
||||
const pendingGameId = builder.createString("public-1");
|
||||
const pendingApplicant = builder.createString("user-1");
|
||||
const pendingRace = builder.createString("Vegan Federation");
|
||||
const pendingStatus = builder.createString("pending");
|
||||
ApplicationSummary.startApplicationSummary(builder);
|
||||
ApplicationSummary.addApplicationId(builder, pendingId);
|
||||
ApplicationSummary.addGameId(builder, pendingGameId);
|
||||
ApplicationSummary.addApplicantUserId(builder, pendingApplicant);
|
||||
ApplicationSummary.addRaceName(builder, pendingRace);
|
||||
ApplicationSummary.addStatus(builder, pendingStatus);
|
||||
ApplicationSummary.addCreatedAtMs(builder, 1_770_000_000_000n);
|
||||
ApplicationSummary.addDecidedAtMs(builder, 0n);
|
||||
const pending = ApplicationSummary.endApplicationSummary(builder);
|
||||
|
||||
const approvedId = builder.createString("app-2");
|
||||
const approvedGameId = builder.createString("public-2");
|
||||
const approvedApplicant = builder.createString("user-1");
|
||||
const approvedRace = builder.createString("Lithic Compact");
|
||||
const approvedStatus = builder.createString("approved");
|
||||
ApplicationSummary.startApplicationSummary(builder);
|
||||
ApplicationSummary.addApplicationId(builder, approvedId);
|
||||
ApplicationSummary.addGameId(builder, approvedGameId);
|
||||
ApplicationSummary.addApplicantUserId(builder, approvedApplicant);
|
||||
ApplicationSummary.addRaceName(builder, approvedRace);
|
||||
ApplicationSummary.addStatus(builder, approvedStatus);
|
||||
ApplicationSummary.addCreatedAtMs(builder, 1_770_000_000_000n);
|
||||
ApplicationSummary.addDecidedAtMs(builder, 1_770_010_000_000n);
|
||||
const approved = ApplicationSummary.endApplicationSummary(builder);
|
||||
|
||||
const items = MyApplicationsListResponse.createItemsVector(builder, [pending, approved]);
|
||||
MyApplicationsListResponse.startMyApplicationsListResponse(builder);
|
||||
MyApplicationsListResponse.addItems(builder, items);
|
||||
builder.finish(MyApplicationsListResponse.endMyApplicationsListResponse(builder));
|
||||
|
||||
const decoded = MyApplicationsListResponse.getRootAsMyApplicationsListResponse(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded.itemsLength()).toBe(2);
|
||||
const first = decoded.items(0)!;
|
||||
expect(first.status()).toBe("pending");
|
||||
expect(first.decidedAtMs()).toBe(0n);
|
||||
const second = decoded.items(1)!;
|
||||
expect(second.status()).toBe("approved");
|
||||
expect(second.decidedAtMs()).toBe(1_770_010_000_000n);
|
||||
});
|
||||
|
||||
test("MyApplicationsListRequest round-trips an empty body", () => {
|
||||
const builder = new Builder(32);
|
||||
MyApplicationsListRequest.startMyApplicationsListRequest(builder);
|
||||
builder.finish(MyApplicationsListRequest.endMyApplicationsListRequest(builder));
|
||||
const decoded = MyApplicationsListRequest.getRootAsMyApplicationsListRequest(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded).toBeDefined();
|
||||
});
|
||||
|
||||
test("InviteSummary preserves invited_user_id and code fields", () => {
|
||||
const builder = new Builder(256);
|
||||
|
||||
const userBoundId = builder.createString("invite-user-bound");
|
||||
const userBoundGame = builder.createString("private-1");
|
||||
const userBoundInviter = builder.createString("user-host");
|
||||
const userBoundInvited = builder.createString("user-1");
|
||||
const userBoundCode = builder.createString("");
|
||||
const userBoundRace = builder.createString("Vegan Federation");
|
||||
const userBoundStatus = builder.createString("pending");
|
||||
InviteSummary.startInviteSummary(builder);
|
||||
InviteSummary.addInviteId(builder, userBoundId);
|
||||
InviteSummary.addGameId(builder, userBoundGame);
|
||||
InviteSummary.addInviterUserId(builder, userBoundInviter);
|
||||
InviteSummary.addInvitedUserId(builder, userBoundInvited);
|
||||
InviteSummary.addCode(builder, userBoundCode);
|
||||
InviteSummary.addRaceName(builder, userBoundRace);
|
||||
InviteSummary.addStatus(builder, userBoundStatus);
|
||||
InviteSummary.addCreatedAtMs(builder, 1_770_000_000_000n);
|
||||
InviteSummary.addExpiresAtMs(builder, 1_780_000_000_000n);
|
||||
InviteSummary.addDecidedAtMs(builder, 0n);
|
||||
const userBound = InviteSummary.endInviteSummary(builder);
|
||||
|
||||
const codeBasedId = builder.createString("invite-code-based");
|
||||
const codeBasedGame = builder.createString("private-2");
|
||||
const codeBasedInviter = builder.createString("user-host");
|
||||
const codeBasedInvited = builder.createString("");
|
||||
const codeBasedCode = builder.createString("ABCDEF12");
|
||||
const codeBasedRace = builder.createString("Lithic Compact");
|
||||
const codeBasedStatus = builder.createString("pending");
|
||||
InviteSummary.startInviteSummary(builder);
|
||||
InviteSummary.addInviteId(builder, codeBasedId);
|
||||
InviteSummary.addGameId(builder, codeBasedGame);
|
||||
InviteSummary.addInviterUserId(builder, codeBasedInviter);
|
||||
InviteSummary.addInvitedUserId(builder, codeBasedInvited);
|
||||
InviteSummary.addCode(builder, codeBasedCode);
|
||||
InviteSummary.addRaceName(builder, codeBasedRace);
|
||||
InviteSummary.addStatus(builder, codeBasedStatus);
|
||||
InviteSummary.addCreatedAtMs(builder, 1_770_000_000_000n);
|
||||
InviteSummary.addExpiresAtMs(builder, 1_780_000_000_000n);
|
||||
InviteSummary.addDecidedAtMs(builder, 0n);
|
||||
const codeBased = InviteSummary.endInviteSummary(builder);
|
||||
|
||||
const items = MyInvitesListResponse.createItemsVector(builder, [userBound, codeBased]);
|
||||
MyInvitesListResponse.startMyInvitesListResponse(builder);
|
||||
MyInvitesListResponse.addItems(builder, items);
|
||||
builder.finish(MyInvitesListResponse.endMyInvitesListResponse(builder));
|
||||
|
||||
const decoded = MyInvitesListResponse.getRootAsMyInvitesListResponse(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded.itemsLength()).toBe(2);
|
||||
const first = decoded.items(0)!;
|
||||
expect(first.invitedUserId()).toBe("user-1");
|
||||
expect(first.code()).toBe("");
|
||||
const second = decoded.items(1)!;
|
||||
expect(second.invitedUserId()).toBe("");
|
||||
expect(second.code()).toBe("ABCDEF12");
|
||||
});
|
||||
|
||||
test("MyInvitesListRequest round-trips an empty body", () => {
|
||||
const builder = new Builder(32);
|
||||
MyInvitesListRequest.startMyInvitesListRequest(builder);
|
||||
builder.finish(MyInvitesListRequest.endMyInvitesListRequest(builder));
|
||||
const decoded = MyInvitesListRequest.getRootAsMyInvitesListRequest(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded).toBeDefined();
|
||||
});
|
||||
|
||||
test("OpenEnrollmentRequest and Response round-trip", () => {
|
||||
const builder = new Builder(64);
|
||||
const gameId = builder.createString("game-private-7c8f");
|
||||
OpenEnrollmentRequest.startOpenEnrollmentRequest(builder);
|
||||
OpenEnrollmentRequest.addGameId(builder, gameId);
|
||||
builder.finish(OpenEnrollmentRequest.endOpenEnrollmentRequest(builder));
|
||||
const reqDecoded = OpenEnrollmentRequest.getRootAsOpenEnrollmentRequest(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(reqDecoded.gameId()).toBe("game-private-7c8f");
|
||||
|
||||
const respBuilder = new Builder(64);
|
||||
const respGameId = respBuilder.createString("game-private-7c8f");
|
||||
const status = respBuilder.createString("enrollment_open");
|
||||
OpenEnrollmentResponse.startOpenEnrollmentResponse(respBuilder);
|
||||
OpenEnrollmentResponse.addGameId(respBuilder, respGameId);
|
||||
OpenEnrollmentResponse.addStatus(respBuilder, status);
|
||||
respBuilder.finish(OpenEnrollmentResponse.endOpenEnrollmentResponse(respBuilder));
|
||||
const respDecoded = OpenEnrollmentResponse.getRootAsOpenEnrollmentResponse(
|
||||
new ByteBuffer(respBuilder.asUint8Array()),
|
||||
);
|
||||
expect(respDecoded.gameId()).toBe("game-private-7c8f");
|
||||
expect(respDecoded.status()).toBe("enrollment_open");
|
||||
});
|
||||
|
||||
test("GameCreateRequest and Response round-trip", () => {
|
||||
const builder = new Builder(256);
|
||||
const name = builder.createString("First Contact");
|
||||
const description = builder.createString("");
|
||||
const turnSchedule = builder.createString("0 0 * * *");
|
||||
const targetVersion = builder.createString("v1");
|
||||
GameCreateRequest.startGameCreateRequest(builder);
|
||||
GameCreateRequest.addGameName(builder, name);
|
||||
GameCreateRequest.addDescription(builder, description);
|
||||
GameCreateRequest.addMinPlayers(builder, 2);
|
||||
GameCreateRequest.addMaxPlayers(builder, 8);
|
||||
GameCreateRequest.addStartGapHours(builder, 24);
|
||||
GameCreateRequest.addStartGapPlayers(builder, 2);
|
||||
GameCreateRequest.addEnrollmentEndsAtMs(builder, 1_780_000_000_000n);
|
||||
GameCreateRequest.addTurnSchedule(builder, turnSchedule);
|
||||
GameCreateRequest.addTargetEngineVersion(builder, targetVersion);
|
||||
builder.finish(GameCreateRequest.endGameCreateRequest(builder));
|
||||
const reqDecoded = GameCreateRequest.getRootAsGameCreateRequest(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(reqDecoded.gameName()).toBe("First Contact");
|
||||
expect(reqDecoded.minPlayers()).toBe(2);
|
||||
expect(reqDecoded.maxPlayers()).toBe(8);
|
||||
expect(reqDecoded.turnSchedule()).toBe("0 0 * * *");
|
||||
expect(reqDecoded.targetEngineVersion()).toBe("v1");
|
||||
expect(reqDecoded.enrollmentEndsAtMs()).toBe(1_780_000_000_000n);
|
||||
|
||||
const respBuilder = new Builder(256);
|
||||
const game = encodeGameSummary(respBuilder, PRIVATE_GAME);
|
||||
GameCreateResponse.startGameCreateResponse(respBuilder);
|
||||
GameCreateResponse.addGame(respBuilder, game);
|
||||
respBuilder.finish(GameCreateResponse.endGameCreateResponse(respBuilder));
|
||||
const respDecoded = GameCreateResponse.getRootAsGameCreateResponse(
|
||||
new ByteBuffer(respBuilder.asUint8Array()),
|
||||
);
|
||||
expectGameSummary(respDecoded.game(), PRIVATE_GAME);
|
||||
});
|
||||
|
||||
test("ApplicationSubmitRequest and Response round-trip", () => {
|
||||
const builder = new Builder(128);
|
||||
const gameId = builder.createString("public-1");
|
||||
const raceName = builder.createString("Vegan Federation");
|
||||
ApplicationSubmitRequest.startApplicationSubmitRequest(builder);
|
||||
ApplicationSubmitRequest.addGameId(builder, gameId);
|
||||
ApplicationSubmitRequest.addRaceName(builder, raceName);
|
||||
builder.finish(ApplicationSubmitRequest.endApplicationSubmitRequest(builder));
|
||||
const reqDecoded = ApplicationSubmitRequest.getRootAsApplicationSubmitRequest(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(reqDecoded.gameId()).toBe("public-1");
|
||||
expect(reqDecoded.raceName()).toBe("Vegan Federation");
|
||||
|
||||
const respBuilder = new Builder(128);
|
||||
const appId = respBuilder.createString("app-3");
|
||||
const appGameId = respBuilder.createString("public-1");
|
||||
const applicant = respBuilder.createString("user-1");
|
||||
const race = respBuilder.createString("Vegan Federation");
|
||||
const status = respBuilder.createString("pending");
|
||||
ApplicationSummary.startApplicationSummary(respBuilder);
|
||||
ApplicationSummary.addApplicationId(respBuilder, appId);
|
||||
ApplicationSummary.addGameId(respBuilder, appGameId);
|
||||
ApplicationSummary.addApplicantUserId(respBuilder, applicant);
|
||||
ApplicationSummary.addRaceName(respBuilder, race);
|
||||
ApplicationSummary.addStatus(respBuilder, status);
|
||||
ApplicationSummary.addCreatedAtMs(respBuilder, 1_770_000_000_000n);
|
||||
ApplicationSummary.addDecidedAtMs(respBuilder, 0n);
|
||||
const app = ApplicationSummary.endApplicationSummary(respBuilder);
|
||||
ApplicationSubmitResponse.startApplicationSubmitResponse(respBuilder);
|
||||
ApplicationSubmitResponse.addApplication(respBuilder, app);
|
||||
respBuilder.finish(ApplicationSubmitResponse.endApplicationSubmitResponse(respBuilder));
|
||||
const respDecoded = ApplicationSubmitResponse.getRootAsApplicationSubmitResponse(
|
||||
new ByteBuffer(respBuilder.asUint8Array()),
|
||||
);
|
||||
const application = respDecoded.application();
|
||||
expect(application).not.toBeNull();
|
||||
expect(application!.applicationId()).toBe("app-3");
|
||||
expect(application!.status()).toBe("pending");
|
||||
});
|
||||
|
||||
test("InviteRedeem and InviteDecline requests round-trip", () => {
|
||||
for (const ctor of [InviteRedeemRequest, InviteDeclineRequest] as const) {
|
||||
const builder = new Builder(128);
|
||||
const gameId = builder.createString("private-1");
|
||||
const inviteId = builder.createString("invite-1");
|
||||
if (ctor === InviteRedeemRequest) {
|
||||
InviteRedeemRequest.startInviteRedeemRequest(builder);
|
||||
InviteRedeemRequest.addGameId(builder, gameId);
|
||||
InviteRedeemRequest.addInviteId(builder, inviteId);
|
||||
builder.finish(InviteRedeemRequest.endInviteRedeemRequest(builder));
|
||||
const decoded = InviteRedeemRequest.getRootAsInviteRedeemRequest(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded.gameId()).toBe("private-1");
|
||||
expect(decoded.inviteId()).toBe("invite-1");
|
||||
} else {
|
||||
InviteDeclineRequest.startInviteDeclineRequest(builder);
|
||||
InviteDeclineRequest.addGameId(builder, gameId);
|
||||
InviteDeclineRequest.addInviteId(builder, inviteId);
|
||||
builder.finish(InviteDeclineRequest.endInviteDeclineRequest(builder));
|
||||
const decoded = InviteDeclineRequest.getRootAsInviteDeclineRequest(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded.gameId()).toBe("private-1");
|
||||
expect(decoded.inviteId()).toBe("invite-1");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("InviteRedeemResponse and InviteDeclineResponse carry an InviteSummary", () => {
|
||||
for (const status of ["accepted", "declined"]) {
|
||||
const builder = new Builder(128);
|
||||
const inviteId = builder.createString("invite-1");
|
||||
const gameId = builder.createString("private-1");
|
||||
const inviter = builder.createString("user-host");
|
||||
const invited = builder.createString("user-1");
|
||||
const code = builder.createString("");
|
||||
const race = builder.createString("Vegan Federation");
|
||||
const statusStr = builder.createString(status);
|
||||
InviteSummary.startInviteSummary(builder);
|
||||
InviteSummary.addInviteId(builder, inviteId);
|
||||
InviteSummary.addGameId(builder, gameId);
|
||||
InviteSummary.addInviterUserId(builder, inviter);
|
||||
InviteSummary.addInvitedUserId(builder, invited);
|
||||
InviteSummary.addCode(builder, code);
|
||||
InviteSummary.addRaceName(builder, race);
|
||||
InviteSummary.addStatus(builder, statusStr);
|
||||
InviteSummary.addCreatedAtMs(builder, 1_770_000_000_000n);
|
||||
InviteSummary.addExpiresAtMs(builder, 1_780_000_000_000n);
|
||||
InviteSummary.addDecidedAtMs(builder, 1_770_010_000_000n);
|
||||
const summary = InviteSummary.endInviteSummary(builder);
|
||||
|
||||
if (status === "accepted") {
|
||||
InviteRedeemResponse.startInviteRedeemResponse(builder);
|
||||
InviteRedeemResponse.addInvite(builder, summary);
|
||||
builder.finish(InviteRedeemResponse.endInviteRedeemResponse(builder));
|
||||
const decoded = InviteRedeemResponse.getRootAsInviteRedeemResponse(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded.invite()?.status()).toBe("accepted");
|
||||
} else {
|
||||
InviteDeclineResponse.startInviteDeclineResponse(builder);
|
||||
InviteDeclineResponse.addInvite(builder, summary);
|
||||
builder.finish(InviteDeclineResponse.endInviteDeclineResponse(builder));
|
||||
const decoded = InviteDeclineResponse.getRootAsInviteDeclineResponse(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
expect(decoded.invite()?.status()).toBe("declined");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("ErrorResponse round-trips a code/message pair", () => {
|
||||
const builder = new Builder(128);
|
||||
const code = builder.createString("conflict");
|
||||
const message = builder.createString("request conflicts with current state");
|
||||
ErrorBody.startErrorBody(builder);
|
||||
ErrorBody.addCode(builder, code);
|
||||
ErrorBody.addMessage(builder, message);
|
||||
const errorOff = ErrorBody.endErrorBody(builder);
|
||||
ErrorResponse.startErrorResponse(builder);
|
||||
ErrorResponse.addError(builder, errorOff);
|
||||
builder.finish(ErrorResponse.endErrorResponse(builder));
|
||||
const decoded = ErrorResponse.getRootAsErrorResponse(
|
||||
new ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
const error = decoded.error();
|
||||
expect(error).not.toBeNull();
|
||||
expect(error!.code()).toBe("conflict");
|
||||
expect(error!.message()).toBe("request conflicts with current state");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,361 @@
|
||||
// Component tests for the Phase 8 lobby page. The lobby API and the
|
||||
// gateway client are mocked at module level; the session singleton is
|
||||
// wired to a per-test `SessionStore`-backing IndexedDB so the page's
|
||||
// boot path settles on `authenticated` and constructs a real
|
||||
// GalaxyClient (which is then never called because the lobby API
|
||||
// wrappers are stubs). The tests assert the section rendering, the
|
||||
// inline race-name form for public games, and the invitation Accept
|
||||
// flow.
|
||||
|
||||
import "fake-indexeddb/auto";
|
||||
import { fireEvent, render, waitFor } from "@testing-library/svelte";
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import type { IDBPDatabase } from "idb";
|
||||
|
||||
import { i18n } from "../src/lib/i18n/index.svelte";
|
||||
import { session } from "../src/lib/session-store.svelte";
|
||||
import { type GalaxyDB, openGalaxyDB } from "../src/platform/store/idb";
|
||||
import { IDBCache } from "../src/platform/store/idb-cache";
|
||||
import { WebCryptoKeyStore } from "../src/platform/store/webcrypto-keystore";
|
||||
|
||||
vi.mock("$app/navigation", () => ({
|
||||
goto: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
const listMyGamesSpy = vi.fn();
|
||||
const listPublicGamesSpy = vi.fn();
|
||||
const listMyInvitesSpy = vi.fn();
|
||||
const listMyApplicationsSpy = vi.fn();
|
||||
const submitApplicationSpy = vi.fn();
|
||||
const redeemInviteSpy = vi.fn();
|
||||
const declineInviteSpy = vi.fn();
|
||||
|
||||
vi.mock("../src/api/lobby", async () => {
|
||||
const actual = await vi.importActual<typeof import("../src/api/lobby")>(
|
||||
"../src/api/lobby",
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
listMyGames: (...args: unknown[]) => listMyGamesSpy(...args),
|
||||
listPublicGames: (...args: unknown[]) => listPublicGamesSpy(...args),
|
||||
listMyInvites: (...args: unknown[]) => listMyInvitesSpy(...args),
|
||||
listMyApplications: (...args: unknown[]) => listMyApplicationsSpy(...args),
|
||||
submitApplication: (...args: unknown[]) => submitApplicationSpy(...args),
|
||||
redeemInvite: (...args: unknown[]) => redeemInviteSpy(...args),
|
||||
declineInvite: (...args: unknown[]) => declineInviteSpy(...args),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../src/lib/env", () => ({
|
||||
GATEWAY_BASE_URL: "http://gateway.test",
|
||||
GATEWAY_RESPONSE_PUBLIC_KEY: new Uint8Array(32).fill(0x55),
|
||||
}));
|
||||
|
||||
vi.mock("../src/api/connect", () => ({
|
||||
createEdgeGatewayClient: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
vi.mock("../src/api/galaxy-client", () => {
|
||||
class FakeGalaxyClient {
|
||||
executeCommand = vi.fn(async () => ({
|
||||
resultCode: "ok",
|
||||
payloadBytes: new Uint8Array(),
|
||||
}));
|
||||
}
|
||||
return { GalaxyClient: FakeGalaxyClient };
|
||||
});
|
||||
|
||||
vi.mock("../src/platform/core/index", () => ({
|
||||
loadCore: async () => ({
|
||||
signRequest: () => new Uint8Array(),
|
||||
verifyResponse: () => true,
|
||||
verifyEvent: () => true,
|
||||
verifyPayloadHash: () => true,
|
||||
}),
|
||||
}));
|
||||
|
||||
let db: IDBPDatabase<GalaxyDB>;
|
||||
let dbName: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbName = `galaxy-ui-test-${crypto.randomUUID()}`;
|
||||
db = await openGalaxyDB(dbName);
|
||||
const store = {
|
||||
keyStore: new WebCryptoKeyStore(db),
|
||||
cache: new IDBCache(db),
|
||||
};
|
||||
session.resetForTests();
|
||||
session.setStoreLoaderForTests(async () => store);
|
||||
await session.init();
|
||||
await session.signIn("device-1");
|
||||
i18n.resetForTests("en");
|
||||
|
||||
listMyGamesSpy.mockReset();
|
||||
listPublicGamesSpy.mockReset();
|
||||
listMyInvitesSpy.mockReset();
|
||||
listMyApplicationsSpy.mockReset();
|
||||
submitApplicationSpy.mockReset();
|
||||
redeemInviteSpy.mockReset();
|
||||
declineInviteSpy.mockReset();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
session.resetForTests();
|
||||
i18n.resetForTests("en");
|
||||
db.close();
|
||||
await new Promise<void>((resolve) => {
|
||||
const req = indexedDB.deleteDatabase(dbName);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => resolve();
|
||||
req.onblocked = () => resolve();
|
||||
});
|
||||
});
|
||||
|
||||
async function importLobbyPage(): Promise<typeof import("../src/routes/lobby/+page.svelte")> {
|
||||
return import("../src/routes/lobby/+page.svelte");
|
||||
}
|
||||
|
||||
const baseDate = new Date("2026-05-07T10:00:00Z");
|
||||
|
||||
function makeGame(id: string, name: string, status = "draft") {
|
||||
return {
|
||||
gameId: id,
|
||||
gameName: name,
|
||||
gameType: "private",
|
||||
status,
|
||||
ownerUserId: "user-1",
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
enrollmentEndsAt: baseDate,
|
||||
createdAt: baseDate,
|
||||
updatedAt: baseDate,
|
||||
};
|
||||
}
|
||||
|
||||
function makePublicGame(id: string, name: string) {
|
||||
return {
|
||||
gameId: id,
|
||||
gameName: name,
|
||||
gameType: "public",
|
||||
status: "enrollment_open",
|
||||
ownerUserId: "",
|
||||
minPlayers: 4,
|
||||
maxPlayers: 12,
|
||||
enrollmentEndsAt: baseDate,
|
||||
createdAt: baseDate,
|
||||
updatedAt: baseDate,
|
||||
};
|
||||
}
|
||||
|
||||
function makeInvite(id: string) {
|
||||
return {
|
||||
inviteId: id,
|
||||
gameId: "private-1",
|
||||
inviterUserId: "host",
|
||||
invitedUserId: "user-1",
|
||||
code: "",
|
||||
raceName: "Vegan Federation",
|
||||
status: "pending",
|
||||
createdAt: baseDate,
|
||||
expiresAt: baseDate,
|
||||
decidedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
function makeApplication(id: string, status: string) {
|
||||
return {
|
||||
applicationId: id,
|
||||
gameId: "public-1",
|
||||
applicantUserId: "user-1",
|
||||
raceName: "Vegan Federation",
|
||||
status,
|
||||
createdAt: baseDate,
|
||||
decidedAt: status === "pending" ? null : baseDate,
|
||||
};
|
||||
}
|
||||
|
||||
describe("lobby page", () => {
|
||||
test("renders empty states for every section when API returns no items", async () => {
|
||||
listMyGamesSpy.mockResolvedValue([]);
|
||||
listPublicGamesSpy.mockResolvedValue({ items: [], page: 1, pageSize: 50, total: 0 });
|
||||
listMyInvitesSpy.mockResolvedValue([]);
|
||||
listMyApplicationsSpy.mockResolvedValue([]);
|
||||
|
||||
const Page = (await importLobbyPage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(ui.getByTestId("lobby-my-games-empty")).toBeInTheDocument();
|
||||
expect(ui.getByTestId("lobby-invitations-empty")).toBeInTheDocument();
|
||||
expect(ui.getByTestId("lobby-applications-empty")).toBeInTheDocument();
|
||||
expect(ui.getByTestId("lobby-public-games-empty")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
test("renders my-game cards and public-game cards when items are present", async () => {
|
||||
listMyGamesSpy.mockResolvedValue([makeGame("private-1", "First Contact")]);
|
||||
listPublicGamesSpy.mockResolvedValue({
|
||||
items: [makePublicGame("public-1", "Open Lobby")],
|
||||
page: 1,
|
||||
pageSize: 50,
|
||||
total: 1,
|
||||
});
|
||||
listMyInvitesSpy.mockResolvedValue([]);
|
||||
listMyApplicationsSpy.mockResolvedValue([]);
|
||||
|
||||
const Page = (await importLobbyPage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(ui.getAllByTestId("lobby-my-game-card").length).toBe(1);
|
||||
expect(ui.getByText("First Contact")).toBeInTheDocument();
|
||||
expect(ui.getByText("Open Lobby")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
test("submitting an application opens the inline form and posts race_name", async () => {
|
||||
listMyGamesSpy.mockResolvedValue([]);
|
||||
listPublicGamesSpy.mockResolvedValue({
|
||||
items: [makePublicGame("public-1", "Open Lobby")],
|
||||
page: 1,
|
||||
pageSize: 50,
|
||||
total: 1,
|
||||
});
|
||||
listMyInvitesSpy.mockResolvedValue([]);
|
||||
listMyApplicationsSpy.mockResolvedValue([]);
|
||||
submitApplicationSpy.mockResolvedValue(makeApplication("app-1", "pending"));
|
||||
|
||||
const Page = (await importLobbyPage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(ui.getByTestId("lobby-public-game-apply")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await fireEvent.click(ui.getByTestId("lobby-public-game-apply"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(ui.getByTestId("lobby-application-form")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await fireEvent.input(ui.getByTestId("lobby-application-race-name"), {
|
||||
target: { value: "Vegan Federation" },
|
||||
});
|
||||
await fireEvent.click(ui.getByTestId("lobby-application-submit"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(submitApplicationSpy).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
"public-1",
|
||||
"Vegan Federation",
|
||||
);
|
||||
expect(ui.getByTestId("lobby-application-card")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
test("submitting an empty race name surfaces a validation error and does not call the API", async () => {
|
||||
listMyGamesSpy.mockResolvedValue([]);
|
||||
listPublicGamesSpy.mockResolvedValue({
|
||||
items: [makePublicGame("public-1", "Open Lobby")],
|
||||
page: 1,
|
||||
pageSize: 50,
|
||||
total: 1,
|
||||
});
|
||||
listMyInvitesSpy.mockResolvedValue([]);
|
||||
listMyApplicationsSpy.mockResolvedValue([]);
|
||||
|
||||
const Page = (await importLobbyPage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("lobby-public-game-apply")).toBeInTheDocument(),
|
||||
);
|
||||
await fireEvent.click(ui.getByTestId("lobby-public-game-apply"));
|
||||
await fireEvent.click(ui.getByTestId("lobby-application-submit"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(ui.getByTestId("lobby-application-error")).toBeInTheDocument();
|
||||
expect(submitApplicationSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test("accepting an invitation calls redeemInvite and removes the card", async () => {
|
||||
listMyGamesSpy.mockResolvedValue([]);
|
||||
listPublicGamesSpy.mockResolvedValue({ items: [], page: 1, pageSize: 50, total: 0 });
|
||||
listMyInvitesSpy.mockResolvedValue([makeInvite("invite-1")]);
|
||||
listMyApplicationsSpy.mockResolvedValue([]);
|
||||
redeemInviteSpy.mockResolvedValue(makeInvite("invite-1"));
|
||||
|
||||
const Page = (await importLobbyPage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("lobby-invite-accept")).toBeInTheDocument(),
|
||||
);
|
||||
|
||||
await fireEvent.click(ui.getByTestId("lobby-invite-accept"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(redeemInviteSpy).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
"private-1",
|
||||
"invite-1",
|
||||
);
|
||||
expect(ui.queryByTestId("lobby-invite-accept")).not.toBeInTheDocument();
|
||||
expect(ui.getByTestId("lobby-invitations-empty")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
test("declining an invitation calls declineInvite and removes the card", async () => {
|
||||
listMyGamesSpy.mockResolvedValue([]);
|
||||
listPublicGamesSpy.mockResolvedValue({ items: [], page: 1, pageSize: 50, total: 0 });
|
||||
listMyInvitesSpy.mockResolvedValue([makeInvite("invite-2")]);
|
||||
listMyApplicationsSpy.mockResolvedValue([]);
|
||||
declineInviteSpy.mockResolvedValue({ ...makeInvite("invite-2"), status: "declined" });
|
||||
|
||||
const Page = (await importLobbyPage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("lobby-invite-decline")).toBeInTheDocument(),
|
||||
);
|
||||
|
||||
await fireEvent.click(ui.getByTestId("lobby-invite-decline"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(declineInviteSpy).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
"private-1",
|
||||
"invite-2",
|
||||
);
|
||||
expect(ui.queryByTestId("lobby-invite-decline")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
test("application status badges localise pending and approved states", async () => {
|
||||
listMyGamesSpy.mockResolvedValue([]);
|
||||
listPublicGamesSpy.mockResolvedValue({ items: [], page: 1, pageSize: 50, total: 0 });
|
||||
listMyInvitesSpy.mockResolvedValue([]);
|
||||
listMyApplicationsSpy.mockResolvedValue([
|
||||
makeApplication("app-1", "pending"),
|
||||
makeApplication("app-2", "approved"),
|
||||
]);
|
||||
|
||||
const Page = (await importLobbyPage()).default;
|
||||
const ui = render(Page);
|
||||
|
||||
await waitFor(() => {
|
||||
const cards = ui.getAllByTestId("lobby-application-card");
|
||||
expect(cards.length).toBe(2);
|
||||
expect(cards[0]!.querySelector(".status")?.textContent?.trim()).toBe("pending");
|
||||
expect(cards[1]!.querySelector(".status")?.textContent?.trim()).toBe("approved");
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user