Files
dragonroll/tests/map-tokens.test.js
Gitea OpenCode Agent d8900cfb7f
All checks were successful
Test / test (push) Successful in 2s
Fix issue #61: Fix tests
2026-10-15 14:20:26 +00:00

354 lines
16 KiB
JavaScript

// Tests for the actor tokens of a map (Syndria98/dragonroll#38): an actor dragged out of the campaign
// sidebar lands on the map as a token, and that token is then moved from cell to cell of the grid.
//
// Same set-up as tests/map-pins.test.js, which the repository root runs without installing anything:
// the express routers are loaded into `node:vm` with their models stubbed, `MapTokens.js` is loaded as
// a plain function, and the last checks read the templates, where the drag and drop wiring itself is
// what has to stay right.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
function readRepoFile(...parts) {
return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
}
// A mongoose query answers whatever `await query` and `query.lean()` answer with, and lets `select()`
// and `sort()` sit in between.
function mongooseQuery(value) {
const result = {
select: () => result,
sort: () => result,
lean: () => Promise.resolve(value),
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
};
return result;
}
// Loads an express router file with every module it requires stubbed out.
function loadRouter(relativeParts, stubs) {
const routes = new Map();
const router = {
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
if (id === "../services/storage") return { single: () => (req, res, next) => next() };
if (!(id in stubs)) throw new Error(`require("${id}") is not stubbed`);
return stubs[id];
};
const moduleStub = { exports: {} };
vm.compileFunction(readRepoFile(...relativeParts), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
async function call(route, { body = {}, query = {}, params = {}, user = { id: "user-1" } } = {}) {
const handlers = routes.get(route);
assert.ok(handlers, `${route} is not mounted`);
const res = { payload: null, json(payload) { this.payload = payload; } };
await handlers[handlers.length - 1]({ body, query, params, user }, res);
return res.payload;
}
return { routes, call };
}
function makeMap(tokens = [], grid = {}) {
return {
_id: "map-1", campaign: "campaign-1", tokens,
gridSize: 50, offsetX: 0, offsetY: 0,
...grid,
save: async () => {}
};
}
function loadMapRoutes({ ownsCampaign = true, maps = [], actors = [] } = {}) {
return loadRouter(["backend", "src", "routes", "map.js"], {
"../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) },
"../models/Map": { findById: (id) => mongooseQuery(maps.find((map) => map._id === id) ?? null) },
"../models/Note": { findOne: () => mongooseQuery(null) },
"../models/Actor": {
findOne: (filter) => mongooseQuery(
actors.some((actor) => actor._id === String(filter._id) && String(actor.campaign) === String(filter.campaign))
? { _id: String(filter._id) }
: null
),
},
// The map list's own folder tree: `/list` reads it and `/update` checks a move
// against it, so the tokens need the model to answer, never what it answers.
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
});
}
function placeTokenRouteTests() {
test("an actor dropped on the map stands in the middle of the cell it landed on", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 124, y: 76 } });
assert.equal(response.status, "ok");
// 50 px cells: 124 falls in the column centred on 125, 76 in the row centred on 75.
assert.deepEqual(map.tokens, [{ actor: "actor-1", x: 125, y: 75 }]);
});
test("a token lands in the cell of a grid that does not start at the corner of the image", async () => {
const map = makeMap([], { gridSize: 40, offsetX: 10, offsetY: 4 });
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 55, y: 20 } });
assert.deepEqual(map.tokens, [{ actor: "actor-1", x: 70, y: 24 }]);
});
test("an actor of another campaign cannot be made to stand on a map", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-2", campaign: "campaign-2" }] });
const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-2", x: 10, y: 10 } });
assert.equal(response.msg, "errors.notfound");
assert.deepEqual(map.tokens, []);
});
test("a map of somebody else's campaign answers unauthorized", async () => {
const map = makeMap();
const api = loadMapRoutes({ ownsCampaign: false, maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const response = await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 10, y: 10 } });
assert.equal(response.msg, "unauthorized");
assert.deepEqual(map.tokens, []);
});
test("placing an actor again moves its token instead of adding a twin", async () => {
const map = makeMap([{ _id: "token-1", actor: "actor-1", x: 25, y: 25 }]);
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", x: 300, y: 224 } });
assert.equal(map.tokens.length, 1);
assert.deepEqual({ ...map.tokens[0] }, { _id: "token-1", actor: "actor-1", x: 325, y: 225 });
});
test("placing a token needs both a map and an actor", async () => {
const map = makeMap();
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
assert.equal((await api.call("POST /place-token", { body: { actor: "actor-1", x: 1, y: 1 } })).msg, "errors.missing-data");
assert.equal((await api.call("POST /place-token", { body: { id: "map-1", x: 1, y: 1 } })).msg, "errors.missing-data");
assert.deepEqual(map.tokens, []);
});
test("removing a token takes the one it is given and keeps the others", async () => {
const map = makeMap([
{ _id: "token-1", actor: "actor-1", x: 25, y: 25 },
{ _id: "token-2", actor: "actor-2", x: 75, y: 25 },
]);
const api = loadMapRoutes({ maps: [map] });
const response = await api.call("POST /remove-token", { body: { id: "map-1", token: "token-1" } });
assert.equal(response.status, "ok");
assert.deepEqual(map.tokens.map((token) => token._id), ["token-2"]);
});
test("removing a token of a map of somebody else keeps its tokens", async () => {
const map = makeMap([{ _id: "token-1", actor: "actor-1", x: 25, y: 25 }]);
const api = loadMapRoutes({ ownsCampaign: false, maps: [map] });
const response = await api.call("POST /remove-token", { body: { id: "map-1", token: "token-1" } });
assert.equal(response.msg, "unauthorized");
assert.equal(map.tokens.length, 1);
});
}
function loadActorRoutes({ ownsCampaign = true, actors = [], deletedCount = 1 } = {}) {
const tokensPulled = [];
const api = loadRouter(["backend", "src", "routes", "actor.js"], {
"../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) },
"../models/Actor": {
findById: (id) => mongooseQuery(
actors.find((actor) => actor._id === id)
? { ...actors.find((actor) => actor._id === id), deleteOne: async () => ({ deletedCount }) }
: null
),
},
"../models/Map": {
// The driver drops the tokens of the actor from every map holding one; what is worth
// keeping here is the filter it is asked to do that with.
updateMany: async (filter, update) => {
tokensPulled.push({ filter, update });
return { modifiedCount: 1 };
},
},
// The actor list's own folder tree, which the delete does not ask after.
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
});
return { api, tokensPulled };
}
function actorDeletionTests() {
test("deleting an actor takes its tokens off the maps", async () => {
const { api, tokensPulled } = loadActorRoutes({ actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const response = await api.call("POST /delete", { body: { id: "actor-1" } });
assert.equal(response.status, "ok");
assert.deepEqual(tokensPulled, [{ filter: { "tokens.actor": "actor-1" }, update: { $pull: { tokens: { actor: "actor-1" } } } }]);
});
test("a token is not left behind by an actor that could not be deleted", async () => {
const { api, tokensPulled } = loadActorRoutes({ ownsCampaign: false, actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const response = await api.call("POST /delete", { body: { id: "actor-1" } });
assert.equal(response.msg, "unauthorized");
assert.deepEqual(tokensPulled, []);
});
}
function loadMapTokensService() {
const source = readRepoFile("frontend", "app", "services", "MapTokens.js");
const body = source
.replace(/import\s*\{[^}]*\}\s*from\s*['"]vue['"];?/, "")
.replace(/export\s*\{/, "return {")
.concat("\n;");
return vm.compileFunction(body, [])();
}
function mapTokensServiceTests() {
const service = loadMapTokensService();
const grid = { gridSize: 50, offsetX: 0, offsetY: 0 };
test("a spot of the image becomes the middle of the cell it stands in", () => {
assert.deepEqual(service.CellCentre({ x: 124, y: 76 }, grid), { x: 125, y: 75 });
assert.deepEqual(service.CellCentre({ x: 125, y: 75 }, grid), { x: 125, y: 75 });
});
test("cells are counted from the grid origin, not from the corner of the image", () => {
const shifted = { gridSize: 40, offsetX: 10, offsetY: 4 };
assert.deepEqual(service.CellCentre({ x: 55, y: 20 }, shifted), { x: 70, y: 24 });
});
test("a token never stands off the top left corner of the map", () => {
assert.deepEqual(service.CellCentre({ x: -8, y: -1 }, grid), { x: 25, y: 25 });
// A grid starting off the image still cannot put a token at a negative pixel.
assert.deepEqual(service.CellCentre({ x: -8, y: -1 }, { gridSize: 40, offsetX: -30, offsetY: 0 }), { x: 0, y: 20 });
});
test("a grid with nothing set is the 50 px grid the backend defaults to", () => {
assert.deepEqual(service.CellCentre({ x: 10, y: 10 }, {}), { x: 25, y: 25 });
assert.deepEqual(service.CellCentre({ x: 10, y: 10 }, undefined), { x: 25, y: 25 });
});
test("a spot that is not a spot centres on nothing", () => {
assert.equal(service.CellCentre({ x: NaN, y: 10 }, grid), null);
assert.equal(service.CellCentre({}, grid), null);
assert.equal(service.CellCentre(undefined, grid), null);
});
test("the arrow keys walk a token over whole cells", () => {
assert.deepEqual(service.MoveByCells({ x: 125, y: 75 }, grid, -1, 2), { x: 75, y: 175 });
assert.deepEqual(service.MoveByCells({ x: 25, y: 25 }, grid, -3, -1), { x: 0, y: 0 });
assert.equal(service.MoveByCells({ x: 25 }, grid, 1, 0), null);
});
test("a token covers the cell it stands on and never shrinks below an icon", () => {
assert.equal(service.TokenSize(grid, 1), 50);
assert.equal(service.TokenSize(grid, 0.2), 18);
assert.equal(service.TokenSize({ gridSize: 80 }, 2), 160);
});
test("the map tells an actor drag from any other drag dropped on it", () => {
const actorDrag = {
dataTransfer: {
types: [service.ACTOR_DRAG_TYPE],
getData: (type) => (type === service.ACTOR_DRAG_TYPE ? "actor-1" : "")
}
};
const noteDrag = { dataTransfer: { types: ["text/plain"], getData: (type) => (type === "text/plain" ? "note-1" : "") } };
assert.equal(service.IsActorDrag(actorDrag), true);
assert.equal(service.ActorDragId(actorDrag), "actor-1");
assert.equal(service.IsActorDrag(noteDrag), false);
assert.equal(service.ActorDragId(noteDrag), null);
assert.equal(service.IsActorDrag(undefined), false);
assert.equal(service.ActorDragId(undefined), null);
});
test("the viewer and the route agree on where a token stands", async () => {
// A drop is snapped while it is dragged and again when it is saved: the token must not jump.
const map = makeMap([], { gridSize: 40, offsetX: 10, offsetY: 4 });
const api = loadMapRoutes({ maps: [map], actors: [{ _id: "actor-1", campaign: "campaign-1" }] });
const spot = { x: 300, y: 220 };
await api.call("POST /place-token", { body: { id: "map-1", actor: "actor-1", ...spot } });
assert.deepEqual({ x: map.tokens[0].x, y: map.tokens[0].y }, service.CellCentre(spot, map));
});
}
function mapViewerTokenWiringTests() {
const pane = readRepoFile("frontend", "app", "components", "viewer", "map", "MapViewerPane.vue");
const sidebar = readRepoFile("frontend", "app", "components", "partials", "ContentSidebar.vue");
test("an actor row of the sidebar can be dragged out of it", () => {
// The actors' block of the sidebar: since the entry lists got their folders the rows
// come from that tree, so the actor row holds its actor as `row.item`.
const actorSection = /<template v-else-if="activeSection === 'actors'">([\s\S]*?)<\/template>\s*\n\s*<template v-else-if="activeSection === 'items'">/
.exec(sidebar)?.[1] ?? "";
const actorRow = /<div v-else class="entity-entry"[^>]*>/.exec(actorSection)?.[0];
assert.ok(actorRow, "expected the actor rows of the sidebar");
assert.match(actorRow, /draggable="true"/);
assert.match(actorRow, /@dragstart="startActorDrag\(\$event, row\.item\)"/);
assert.match(sidebar, /setData\(ACTOR_DRAG_TYPE, String\(actor\._id\)\)/);
});
test("the map viewport takes the actor drag and places it", () => {
const viewport = /<div[^>]*ref="viewport"[\s\S]*?>/.exec(pane)?.[0];
assert.ok(viewport, "expected the map viewport element");
assert.match(viewport, /@dragover="onMapDragOver"/);
assert.match(viewport, /@drop\.prevent="onMapDrop"/);
});
test("tokens are drawn in screen space, sized by their cell, and only they catch the mouse", () => {
assert.match(pane, /class="map-token"[^>]*:style="tokenStyle\(token\)"/);
assert.match(pane, /\.map-tokens\s*\{[^}]*pointer-events:\s*none/);
assert.match(pane, /\.map-token\s*\{[^}]*pointer-events:\s*auto/);
});
test("dragging a token moves it and does not pan the map", () => {
assert.match(pane, /@pointerdown="onTokenPointerDown\(\$event, token\)"/);
assert.match(pane, /@pointermove="onTokenPointerMove"/);
assert.match(pane, /@pointerup="onTokenPointerUp"/);
// The pane stops the pointer before the viewport ever sees it, so holding a token never pans.
assert.match(pane, /function onTokenPointerDown\(event, token\) \{[^}]*?event\.stopPropagation\(\)/);
});
test("a token answers to the keyboard and its own menu", () => {
assert.match(pane, /@keydown="onTokenKeydown\(\$event, token\)"/);
assert.match(pane, /@contextmenu\.stop\.prevent="onTokenContextMenu\(token\)"/);
});
test("tokens are saved and taken off through the map routes", () => {
assert.match(pane, /['"]\/map\/place-token['"]/);
assert.match(pane, /['"]\/map\/remove-token['"]/);
});
}
placeTokenRouteTests();
actorDeletionTests();
mapTokensServiceTests();
mapViewerTokenWiringTests();