605 lines
29 KiB
JavaScript
605 lines
29 KiB
JavaScript
// Tests for Syndria98/dragonroll#83, the things the character sheet did not hold:
|
|
// * the eighteen skills down the ability scores tab, each with a circle that stands lit
|
|
// when the character is proficient with it, and the six saving throws beside them,
|
|
// * proficiencies with tools and with languages,
|
|
// * the coins a character carries and the icon of each item it carries,
|
|
// * and traits that reach the campaign from the linked Foundry world.
|
|
//
|
|
// The window is a `.vue` file and the repository root installs no dependencies for it, so
|
|
// its template, styles and plain functions are read out of the source the way
|
|
// tests/character-sheet-tabs.test.js and tests/character-sheet-portrait-column.test.js
|
|
// read them. The Foundry mapper is plain CommonJS and is required for real; the actor
|
|
// route runs in a stubbed `require` against fake models, like tests/foundry-force-import.test.js.
|
|
// The Foundry module goes into a `node:vm` context with stubbed globals, like
|
|
// tests/foundry-sync-toggle.test.js, so what its actor snapshot carries is observable.
|
|
//
|
|
// 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");
|
|
|
|
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
|
const MODULE_ID = "dragonroll-foundry";
|
|
|
|
const sheetSource = read("frontend", "app", "components", "windows", "CharacterSheetWindow.vue");
|
|
const script = /<script setup>([\s\S]*?)<\/script>/.exec(sheetSource)?.[1] ?? "";
|
|
const template = /<template>([\s\S]*)<\/template>/.exec(sheetSource)?.[1] ?? "";
|
|
const actorModelSource = read("backend", "src", "models", "Actor.js");
|
|
|
|
// `fromSource` hands back one top-level declaration as a value, like the other character
|
|
// sheet tests do it.
|
|
function fromSource(source, pattern, locals = {}) {
|
|
const declaration = pattern.exec(source)?.[0];
|
|
assert.ok(declaration, `expected ${pattern} in the source`);
|
|
const name = /(?:const|function)\s+(\w+)/.exec(declaration)[1];
|
|
return new Function(...Object.keys(locals), `${declaration}\n;return ${name};`)(...Object.values(locals));
|
|
}
|
|
|
|
const abilityStats = fromSource(script, /const abilityStats = \[[\s\S]*?\];/);
|
|
const skillList = fromSource(script, /const skillList = \[[\s\S]*?\];/);
|
|
const currencyUnits = fromSource(script, /const currencyUnits = \[[\s\S]*?\];/);
|
|
const proficiencyText = fromSource(script, /function proficiencyText\(value\) \{[\s\S]*?\n\}/);
|
|
const proficiencyList = fromSource(script, /function proficiencyList\(text\) \{[\s\S]*?\n\}/);
|
|
const normalizeActor = fromSource(script, /function normalizeActor\(actor\) \{[\s\S]*?\n\}/, {
|
|
abilityStats, skillList, currencyUnits, proficiencyText
|
|
});
|
|
|
|
const skillKeys = skillList.map(({ key }) => key);
|
|
|
|
// --- The sheet: skills and saving throws on the ability scores tab -----------------
|
|
|
|
test("the sheet knows the eighteen skills, each under the ability that manages it", () => {
|
|
assert.deepEqual(skillKeys, [
|
|
"acrobatics", "animalHandling", "arcana", "athletics", "deception", "history", "insight",
|
|
"intimidation", "investigation", "medicine", "nature", "perception", "performance",
|
|
"persuasion", "religion", "sleightOfHand", "stealth", "survival"
|
|
]);
|
|
assert.deepEqual(
|
|
skillList.map(({ ability }) => ability),
|
|
["dex", "wis", "int", "str", "cha", "int", "wis", "cha", "int", "wis", "int", "wis", "cha", "cha", "int", "dex", "dex", "wis"],
|
|
"each skill stands with the ability D&D counts for it"
|
|
);
|
|
});
|
|
|
|
test("every skill stands with a circle that toggles whether the character is proficient", () => {
|
|
const panel = /<section class="sheet-panel skills-panel">([\s\S]*?)<\/section>/.exec(template)?.[1] ?? "";
|
|
assert.match(panel, /campaigns\.character-sheet\.skills/, "the panel is named for the skills");
|
|
assert.match(panel, /v-for="skill in skillList"/);
|
|
assert.match(panel, /:aria-checked="form\.skills\[skill\.key\]"/, "the circle says what it holds");
|
|
assert.match(panel, /@click="toggleProficiency\('skills', skill\.key\)"/);
|
|
assert.match(panel, /class="proficiency-dot"/);
|
|
assert.match(panel, /\{ proficient: form\.skills\[skill\.key\] \}/, "the circle stands lit for a proficiency");
|
|
assert.match(panel, /campaigns\.character-sheet\.skill-names\.\$\{skill\.key\}/, "the skill is called by its name");
|
|
assert.match(panel, /\{\{ skillModifier\(skill\) \}\}/, "and it shows the modifier the character rolls with it");
|
|
|
|
const toggle = /function toggleProficiency\(group, key\) \{[\s\S]*?\n\}/.exec(script)?.[0];
|
|
assert.match(toggle, /form\.value\[group\]\[key\] = !form\.value\[group\]\[key\]/, "the circle flips the toggle");
|
|
// The toggles belong to an edit in progress, like every other field of the sheet.
|
|
assert.match(panel, /:disabled="!editing"/);
|
|
});
|
|
|
|
test("the six saving throws ride with the ability scores", () => {
|
|
const abilities = /<section class="sheet-panel abilities-panel">([\s\S]*?)<\/section>/.exec(template)?.[1] ?? "";
|
|
assert.match(abilities, /campaigns\.character-sheet\.saving-throws/);
|
|
assert.match(abilities, /v-for="stat in abilityStats"/, "one save per ability score");
|
|
assert.match(abilities, /:aria-checked="form\.savingThrows\[stat\.key\]"/);
|
|
assert.match(abilities, /@click="toggleProficiency\('savingThrows', stat\.key\)"/);
|
|
assert.match(abilities, /\{\{ savingThrowModifier\(stat\) \}\}/);
|
|
// The ability scores themselves are untouched, and the saves stand under them.
|
|
assert.match(abilities, /v-model\.number="form\.abilityScores\[stat\.key\]"/);
|
|
assert.ok(
|
|
abilities.indexOf("ability-grid") < abilities.indexOf("saving-throw-grid"),
|
|
"the saving throws follow the scores they come from"
|
|
);
|
|
});
|
|
|
|
test("a skill's form entry starts off, and the world's toggles carry over", () => {
|
|
const fresh = normalizeActor({});
|
|
assert.deepEqual(fresh.skills.acrobatics, false);
|
|
assert.deepEqual(fresh.savingThrows.str, false);
|
|
assert.deepEqual(Object.keys(fresh.skills).length, 18, "every skill stands in the form, toggled or not");
|
|
assert.deepEqual(Object.keys(fresh.savingThrows).sort(), ["cha", "con", "dex", "int", "str", "wis"]);
|
|
|
|
const trained = normalizeActor({ skills: { stealth: true }, savingThrows: { con: true } });
|
|
assert.equal(trained.skills.stealth, true);
|
|
assert.equal(trained.savingThrows.con, true);
|
|
});
|
|
|
|
// --- Tools and languages ----------------------------------------------------------
|
|
|
|
test("tools and languages have a list of their own under the proficiencies", () => {
|
|
const panel = /<section class="sheet-panel proficiencies-panel">([\s\S]*?)<\/section>/.exec(template)?.[1] ?? "";
|
|
for (const [key, field] of [["tools", "form.tools"], ["languages", "form.languages"]]) {
|
|
assert.match(panel, new RegExp(`campaigns\\.character-sheet\\.${key}`), `the ${key} are named`);
|
|
assert.match(panel, new RegExp(`v-model="${field}"`), `the ${key} are edited as text`);
|
|
assert.match(panel, new RegExp(`\\{\\{ ${field} \\|\\| \\$t\\('campaigns\\.character-sheet\\.empty-${key}'\\) \\}\\}`));
|
|
}
|
|
// The free text keeps what has no list of its own, so it no longer asks for these.
|
|
const placeholder = /"proficiencies-placeholder": "([^"]+)"/.exec(read("frontend", "i18n", "locales", "en", "campaigns.json"))[1];
|
|
assert.doesNotMatch(placeholder, /skills|saving throws|tools|languages/i, "the text field does not ask for what has its own list");
|
|
});
|
|
|
|
test("the tools and languages lists travel as a list and edit as one name per line", () => {
|
|
assert.deepEqual(normalizeActor({ tools: ["Thieves tools", "Dice set"] }).tools, "Thieves tools\nDice set");
|
|
assert.deepEqual(normalizeActor({ languages: [] }).languages, "");
|
|
assert.deepEqual(
|
|
normalizeActor({ tools: [" Thieves tools ", "Thieves tools", "", "Dice set"] }).tools,
|
|
"Thieves tools\nDice set",
|
|
"blanks, spaces and repeats are not kept"
|
|
);
|
|
assert.deepEqual(proficiencyList("Thieves tools\nDice set"), ["Thieves tools", "Dice set"]);
|
|
assert.deepEqual(proficiencyList("Common, Elvish, Common"), ["Common", "Elvish"], "a comma separates too");
|
|
assert.deepEqual(proficiencyList(""), []);
|
|
assert.deepEqual(proficiencyList(proficiencyText(["Cartographer's supplies"])), ["Cartographer's supplies"]);
|
|
});
|
|
|
|
// --- Currency and item icons on the inventory tab ---------------------------------
|
|
|
|
test("the inventory shows the coins the character carries", () => {
|
|
assert.deepEqual(currencyUnits, ["pp", "gp", "ep", "sp", "cp"]);
|
|
const panel = /<main v-show="activeTab === 'inventory'"[\s\S]*?<\/main>/.exec(template)?.[0] ?? "";
|
|
assert.match(panel, /campaigns\.character-sheet\.currency/);
|
|
assert.match(panel, /v-for="unit in currencyUnits"/);
|
|
assert.match(panel, /v-model\.number="form\.currency\[unit\]"/, "each coin can be counted in");
|
|
assert.match(panel, /\{\{ form\.currency\[unit\] \}\}/, "and reads back outside of editing");
|
|
|
|
assert.deepEqual(normalizeActor({}).currency, { pp: 0, gp: 0, ep: 0, sp: 0, cp: 0 });
|
|
assert.deepEqual(normalizeActor({ currency: { gp: 12, cp: "40" } }).currency, { pp: 0, gp: 12, ep: 0, sp: 0, cp: 40 });
|
|
});
|
|
|
|
test("every inventory row opens with the item's icon", () => {
|
|
const panel = /<main v-show="activeTab === 'inventory'"[\s\S]*?<\/main>/.exec(template)?.[0] ?? "";
|
|
const iconCell = /<td class="item-icon-cell">([\s\S]*?)<\/td>/.exec(panel)?.[1] ?? "";
|
|
assert.match(iconCell, /v-if="item\.icon"/);
|
|
assert.match(iconCell, /:src="resolveImage\(item\.icon\)"/, "a world's own icon and an upload both resolve");
|
|
assert.match(iconCell, /item-icon-blank/, "and a row without one leaves the place marked");
|
|
|
|
// The icon comes first, and the name it stands in front of keeps reading left.
|
|
const firstCells = /<tr v-for="\(item, index\) in form\.inventory" :key="index">([\s\S]*?)<\/td>\s*([\s\S]*?)<\/td>/.exec(panel);
|
|
assert.match(firstCells[1], /item-icon-cell/);
|
|
assert.match(firstCells[2], /item-name-cell/);
|
|
const aligns = /\.inventory-table th:not\(:first-child\):not\(\.item-name-cell\)/.exec(sheetSource)?.[0];
|
|
assert.ok(aligns, "the name column is let go of the centred columns");
|
|
|
|
assert.equal(normalizeActor({ inventory: [{ name: "Torch" }] }).inventory[0].icon, "");
|
|
assert.equal(
|
|
normalizeActor({ inventory: [{ name: "Torch", icon: "http://vtt.test/icons/torch.svg" }] }).inventory[0].icon,
|
|
"http://vtt.test/icons/torch.svg"
|
|
);
|
|
});
|
|
|
|
// --- The model and the route ------------------------------------------------------
|
|
|
|
test("the Actor model holds the skills, the saves, the tools, the languages and the coins", () => {
|
|
for (const key of skillKeys) {
|
|
assert.match(actorModelSource, new RegExp(`${key}: \\{ type: Boolean, default: false \\}`), `${key} is a toggle`);
|
|
}
|
|
for (const key of ["str", "dex", "con", "int", "wis", "cha"]) {
|
|
assert.ok(
|
|
new RegExp(`savingThrows: \\{[\\s\\S]*?${key}: \\{ type: Boolean, default: false \\}`).test(actorModelSource),
|
|
`the ${key} saving throw stands in the model`
|
|
);
|
|
}
|
|
assert.match(actorModelSource, /tools: \[\{ type: String, trim: true \}\]/);
|
|
assert.match(actorModelSource, /languages: \[\{ type: String, trim: true \}\]/);
|
|
for (const unit of currencyUnits) {
|
|
assert.ok(
|
|
new RegExp(`currency: \\{[\\s\\S]*?${unit}: \\{ type: Number, min: 0, default: 0 \\}`).test(actorModelSource),
|
|
`${unit} counts among the coins`
|
|
);
|
|
}
|
|
assert.match(actorModelSource, /icon: \{ type: String, default: '' \}/, "a carried item keeps its icon");
|
|
});
|
|
|
|
// The actor update route with every require stubbed, the way
|
|
// tests/foundry-force-import.test.js runs the import route.
|
|
function loadActorRoute(actor) {
|
|
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 === "../models/Campaign") {
|
|
return { findOne: () => ({ lean: () => Promise.resolve({ _id: "campaign-1" }) }) };
|
|
}
|
|
if (id === "../models/Actor") return { findById: async () => actor };
|
|
if (id === "../models/Folder") return { belongsToSection: async () => true };
|
|
if (id === "../models/Map") return { updateMany: async () => ({}) };
|
|
throw new Error(`require("${id}") is not stubbed`);
|
|
};
|
|
|
|
const moduleStub = { exports: {} };
|
|
vm.compileFunction(read("backend", "src", "routes", "actor.js"), ["require", "module", "exports"])(
|
|
requireStub, moduleStub, moduleStub.exports
|
|
);
|
|
|
|
async function update(body, user = { id: "user-1" }) {
|
|
const handlers = routes.get("POST /update");
|
|
assert.ok(handlers, "POST /update is not mounted");
|
|
let payload = null;
|
|
await handlers[handlers.length - 1]({ body, user }, { json: (sent) => { payload = sent; } });
|
|
return payload;
|
|
}
|
|
|
|
return { update };
|
|
}
|
|
|
|
test("the actor update writes the skills, the saves, the tools, the languages and the coins", async () => {
|
|
const actor = { _id: "actor-1", campaign: "campaign-1", save: async () => {} };
|
|
const route = loadActorRoute(actor);
|
|
|
|
const response = await route.update({
|
|
id: "actor-1",
|
|
skills: { acrobatics: true, stealth: false },
|
|
savingThrows: { con: true },
|
|
tools: [" Thieves tools ", "Thieves tools", "", "Dice set"],
|
|
languages: ["Elvish", "Undercommon"],
|
|
currency: { gp: 12, cp: 40 },
|
|
inventory: [{ name: "Torch", quantity: 2, weight: 0.5, icon: "icons/torch.svg" }],
|
|
});
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.deepEqual(actor.skills, { acrobatics: true, stealth: false });
|
|
assert.deepEqual(actor.savingThrows, { con: true });
|
|
assert.deepEqual(actor.tools, ["Thieves tools", "Dice set"], "blanks and repeats are written out of the lists");
|
|
assert.deepEqual(actor.languages, ["Elvish", "Undercommon"]);
|
|
assert.deepEqual(actor.currency, { gp: 12, cp: 40 });
|
|
assert.deepEqual(actor.inventory, [{ name: "Torch", quantity: 2, weight: 0.5, icon: "icons/torch.svg" }]);
|
|
});
|
|
|
|
test("an update that says nothing about them leaves the toggles and lists where they are", async () => {
|
|
const actor = {
|
|
_id: "actor-1",
|
|
campaign: "campaign-1",
|
|
skills: { acrobatics: true },
|
|
tools: ["Disguise kit"],
|
|
currency: { gp: 3 },
|
|
save: async () => {},
|
|
};
|
|
const route = loadActorRoute(actor);
|
|
|
|
const response = await route.update({ id: "actor-1", name: "Thalia" });
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.equal(actor.name, "Thalia");
|
|
assert.deepEqual(actor.skills, { acrobatics: true });
|
|
assert.deepEqual(actor.tools, ["Disguise kit"]);
|
|
assert.deepEqual(actor.currency, { gp: 3 });
|
|
});
|
|
|
|
// --- The Foundry world fills them in ---------------------------------------------
|
|
|
|
const { foundryActorToCharacter } = require(path.join(__dirname, "..", "backend", "src", "services", "actor-foundry.js"));
|
|
|
|
test("a world's skill and saving throw proficiencies arrive toggled", () => {
|
|
const character = foundryActorToCharacter({
|
|
name: "Thalia",
|
|
system: {
|
|
skills: { acr: { value: 1 }, stl: { value: 0 }, prc: { value: 2 }, arc: { value: ["exp"] }, his: { value: [] } },
|
|
savingThrows: { str: { value: 1 }, dex: { value: 0 }, con: { prof: { value: 2 } } },
|
|
},
|
|
});
|
|
|
|
assert.deepEqual(character.skills, {
|
|
acrobatics: true, stealth: false, arcana: true, history: false, perception: true,
|
|
});
|
|
assert.deepEqual(character.savingThrows, { str: true, dex: false, con: true });
|
|
});
|
|
|
|
test("an older world holding its saves under the abilities is read the same way", () => {
|
|
const character = foundryActorToCharacter({
|
|
name: "Thalia",
|
|
system: { abilities: { str: { save: 0 }, dex: { save: 1 } }, saves: { con: { proficient: true } } },
|
|
});
|
|
|
|
assert.deepEqual(character.savingThrows, { str: false, dex: true, con: true });
|
|
});
|
|
|
|
test("a world that says nothing about skills or saves leaves what the campaign toggled", () => {
|
|
const character = foundryActorToCharacter({ name: "Thalia", system: { abilities: { str: { value: 16 } } } });
|
|
|
|
assert.ok(!("skills" in character), "no skills to report is not the same as none proficient");
|
|
assert.ok(!("savingThrows" in character));
|
|
assert.ok(!("currency" in character));
|
|
assert.ok(!("tools" in character), "and neither are the tool and language lists");
|
|
assert.ok(!("languages" in character));
|
|
});
|
|
|
|
test("the tools and languages the module names come over as they are named", () => {
|
|
const character = foundryActorToCharacter({
|
|
name: "Thalia",
|
|
system: { traits: { tool: { value: ["xyz12abc345def67"] }, languages: { value: ["aB3cD9eF1gH2iJ4k"] } } },
|
|
dragonroll: { tools: ["Thieves' tools", "Dice set"], languages: ["Elvish", "Deep Speech"] },
|
|
});
|
|
|
|
assert.deepEqual(character.tools, ["Thieves' tools", "Dice set"]);
|
|
assert.deepEqual(character.languages, ["Elvish", "Deep Speech"]);
|
|
});
|
|
|
|
test("without the module's names the proficiency keys are read off the actor", () => {
|
|
const character = foundryActorToCharacter({
|
|
name: "Thalia",
|
|
system: {
|
|
traits: {
|
|
tool: { value: ["thieves", "alchemist"], custom: "Dice set, Playing cards" },
|
|
languages: { value: ["common", "aB3cD9eF1gH2iJ4k"], custom: "Thieves' cant" },
|
|
},
|
|
},
|
|
});
|
|
|
|
assert.deepEqual(character.tools, ["thieves", "alchemist", "Dice set", "Playing cards"]);
|
|
assert.deepEqual(
|
|
character.languages,
|
|
["common", "Thieves' cant"],
|
|
"a language the sheet cannot name is dropped rather than shown as a document id"
|
|
);
|
|
|
|
const none = foundryActorToCharacter({ name: "Thalia", system: { traits: { tool: { value: [] } } } });
|
|
assert.deepEqual(none.tools, [], "a world with no tool proficiency says so");
|
|
assert.ok(!("languages" in none), "and says nothing at all about the ones it does not list");
|
|
});
|
|
|
|
test("the coins of the world are the coins of the campaign", () => {
|
|
const character = foundryActorToCharacter({ name: "Thalia", system: { currency: { pp: 1, gp: 25, sp: -3 } } });
|
|
|
|
assert.deepEqual(character.currency, { pp: 1, gp: 25, ep: 0, sp: 0, cp: 0 }, "and never a debt");
|
|
});
|
|
|
|
test("a carried item brings its own icon", () => {
|
|
const character = foundryActorToCharacter({
|
|
name: "Thalia",
|
|
items: [
|
|
{ name: "Longsword", type: "weapon", img: "http://vtt.test/icons/sword.svg", system: { quantity: 1, weight: { value: 3 } } },
|
|
{ name: "Rope", type: "equipment", system: { quantity: 2 } },
|
|
],
|
|
});
|
|
|
|
assert.deepEqual(character.inventory, [
|
|
{ name: "Longsword", quantity: 1, weight: 3, icon: "http://vtt.test/icons/sword.svg" },
|
|
{ name: "Rope", quantity: 2, weight: 0, icon: "" },
|
|
]);
|
|
});
|
|
|
|
// --- The traits tab syncs --------------------------------------------------------
|
|
|
|
test("the world's own traits reach the campaign", () => {
|
|
const fromText = foundryActorToCharacter({ name: "Thalia", system: { details: { trait: "Spellcaster.<br>Light sleeper." } } });
|
|
assert.equal(fromText.traits, "Spellcaster.\nLight sleeper.");
|
|
|
|
const fromFeatures = foundryActorToCharacter({
|
|
name: "Thalia",
|
|
system: {},
|
|
items: [
|
|
{ name: "Darkvision", type: "feat", system: { featType: "trs", description: { value: "<p>See in the dark.</p>" } } },
|
|
{ name: "Brave", type: "feat", system: { featType: ["tr"], description: { value: "Advantage on saves." } } },
|
|
{ name: "Alert", type: "feat", system: { featType: "feat", description: { value: "Never surprised." } } },
|
|
],
|
|
});
|
|
assert.equal(fromFeatures.traits, "Darkvision\nSee in the dark.\n\nBrave\nAdvantage on saves.");
|
|
});
|
|
|
|
test("the world leads the traits tab, and what the campaign wrote fills in when it has none", () => {
|
|
// The module carries whatever the campaign shows for the traits back to the world on
|
|
// its flag, and the actor's own traits lead from there: a world keeps its traits in
|
|
// step the same way it keeps its proficiencies in step, while a character the world
|
|
// says nothing about keeps what the campaign wrote for it.
|
|
const fromWorld = foundryActorToCharacter({
|
|
name: "Thalia",
|
|
system: { details: { trait: "The world's own traits" } },
|
|
flags: { [MODULE_ID]: { traits: "What the campaign typed" } },
|
|
});
|
|
assert.equal(fromWorld.traits, "The world's own traits");
|
|
|
|
const fromCampaign = foundryActorToCharacter({
|
|
name: "Thalia",
|
|
system: {},
|
|
flags: { [MODULE_ID]: { traits: "What the campaign typed" } },
|
|
});
|
|
assert.equal(fromCampaign.traits, "What the campaign typed");
|
|
});
|
|
|
|
test("an actor that holds no traits does not clear what the campaign has", () => {
|
|
const character = foundryActorToCharacter({ name: "Thalia", system: {}, items: [], flags: {} });
|
|
|
|
assert.ok(!("traits" in character), "a live edit that knows nothing about traits leaves the tab as it is");
|
|
});
|
|
|
|
// A forced actor sync from the module's context menu replaces everything the campaign
|
|
// holds for that actor (Syndria98/dragonroll#96): the fields a live edit leaves out when
|
|
// the world says nothing are written empty instead of kept, and the campaign's own text
|
|
// on the actor's flag does not survive it.
|
|
test("a forced sync writes empty the fields a live edit would leave out", () => {
|
|
const actor = {
|
|
name: "Thalia",
|
|
system: {},
|
|
items: [],
|
|
flags: { [MODULE_ID]: { traits: "What the campaign typed", proficiencies: "Armour, tools" } },
|
|
};
|
|
|
|
const live = foundryActorToCharacter(actor);
|
|
assert.equal(live.traits, "What the campaign typed", "a live edit fills the traits tab from the actor's flag");
|
|
assert.equal(live.proficiencies, "Armour, tools", "and the free-text proficiencies from it too");
|
|
assert.ok(
|
|
!("tools" in live) && !("languages" in live) && !("skills" in live) && !("savingThrows" in live) && !("currency" in live),
|
|
"and says nothing about the toggles and lists the world has no data for"
|
|
);
|
|
|
|
const replaced = foundryActorToCharacter(actor, true);
|
|
assert.equal(replaced.traits, "", "a forced sync clears the traits the campaign typed");
|
|
assert.equal(replaced.proficiencies, "", "down to the free-text proficiencies");
|
|
assert.deepEqual(replaced.tools, []);
|
|
assert.deepEqual(replaced.languages, []);
|
|
assert.deepEqual(replaced.skills, {});
|
|
assert.deepEqual(replaced.savingThrows, {});
|
|
assert.deepEqual(replaced.currency, {});
|
|
});
|
|
|
|
// --- The module sends the names a sheet outside Foundry can read -----------------
|
|
|
|
function makeWorld({ actor, config = {}, worldItems = [] }) {
|
|
const state = { hooks: new Map(), requests: [], timers: new Map(), nextTimerId: 1 };
|
|
const documents = [actor];
|
|
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
|
|
|
|
const sandbox = {
|
|
console: { log() {}, info() {}, warn() {}, error() {} },
|
|
URL,
|
|
CONFIG: config,
|
|
window: { location: { origin: "http://vtt.test" } },
|
|
ui: { notifications: { info() {}, warn() {}, error() {} } },
|
|
Hooks: {
|
|
once(name, fn) { state.hooks.set(name, [fn]); },
|
|
on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); },
|
|
},
|
|
setTimeout: (fn) => { const id = state.nextTimerId++; state.timers.set(id, { fn }); return id; },
|
|
clearTimeout: (id) => state.timers.delete(id),
|
|
setInterval: () => 0,
|
|
clearInterval: () => {},
|
|
fetch: async (url, options = {}) => {
|
|
state.requests.push({ href: String(url), body: options.body ? JSON.parse(options.body) : null });
|
|
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
|
|
},
|
|
Actor: { async create() { return null; } },
|
|
Item: { async create() { return null; } },
|
|
};
|
|
|
|
sandbox.game = {
|
|
user: { isGM: true },
|
|
world: { id: "world-1", title: "Test World" },
|
|
system: { id: "dnd5e" },
|
|
modules: { get: () => ({}) },
|
|
actors: { contents: documents, get: (id) => documents.find((document) => document.id === id) },
|
|
items: { contents: worldItems, get: (id) => worldItems.find((document) => document.id === id) },
|
|
folders: { contents: [], get: () => null },
|
|
settings: {
|
|
register(module, key, definition) {
|
|
if (!(key in settingsStore)) settingsStore[key] = definition.default;
|
|
},
|
|
get(module, key) { return settingsStore[key]; },
|
|
async set(module, key, value) { settingsStore[key] = value; },
|
|
},
|
|
};
|
|
|
|
vm.createContext(sandbox);
|
|
vm.runInContext(read("dragonroll-foundry", "scripts", "api.js"), sandbox);
|
|
|
|
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
|
|
state.fire = async (name, ...args) => {
|
|
for (const handler of state.hooks.get(name) || []) await handler(...args);
|
|
await drain();
|
|
};
|
|
state.runTimers = async () => {
|
|
for (let round = 0; round < 6; round += 1) {
|
|
const due = [...state.timers.values()];
|
|
state.timers.clear();
|
|
for (const timer of due) await timer.fn();
|
|
await drain();
|
|
}
|
|
};
|
|
// Only the pushes of an actor count here: the world start sends one, and what an
|
|
// actor changed sends the next.
|
|
state.actorPushes = () => state.requests
|
|
.filter((request) => request.href.includes("foundry/sync/snapshot"))
|
|
.map((request) => request.body.actors[0]);
|
|
|
|
return state;
|
|
}
|
|
|
|
function makeStubActor(id, name, system = {}, items = []) {
|
|
return {
|
|
id,
|
|
name,
|
|
type: "character",
|
|
documentName: "Actor",
|
|
img: "icons/svg/mystery-man.svg",
|
|
system,
|
|
flags: {},
|
|
items: { contents: items },
|
|
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
|
async update(data) { return data; },
|
|
toObject() { return { _id: this.id, name: this.name, type: this.type, img: this.img, flags: this.flags, system: this.system }; },
|
|
};
|
|
}
|
|
|
|
// A world document of its own — a language since the third release of the system —
|
|
// plain enough to serialize like any other item of the world.
|
|
function makeWorldItem(id, name) {
|
|
return {
|
|
id,
|
|
name,
|
|
type: "loot",
|
|
documentName: "Item",
|
|
parent: null,
|
|
folder: null,
|
|
flags: {},
|
|
system: {},
|
|
getFlag() { return undefined; },
|
|
toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags, system: this.system }; },
|
|
};
|
|
}
|
|
|
|
async function pushAfterEdit(actor, options) {
|
|
const world = makeWorld(options);
|
|
await world.fire("init");
|
|
await world.fire("ready");
|
|
await world.runTimers();
|
|
await world.fire("updateActor", actor);
|
|
await world.runTimers();
|
|
return world.actorPushes().at(-1);
|
|
}
|
|
|
|
test("the actor snapshot names the world's tools and languages", async () => {
|
|
const actor = makeStubActor("actor-1", "Thalia", {
|
|
traits: {
|
|
tool: { value: ["thieves"], custom: "Dice set" },
|
|
languages: { value: ["common", "lang-1"] },
|
|
},
|
|
});
|
|
|
|
const sent = await pushAfterEdit(actor, {
|
|
config: {
|
|
DND5E: {
|
|
tools: { thieves: { label: "Thieves' tools" } },
|
|
languages: { common: { name: "Common" } },
|
|
},
|
|
},
|
|
worldItems: [makeWorldItem("lang-1", "Deep Speech")],
|
|
});
|
|
|
|
assert.equal(sent._id, "actor-1", "the actor the world edited is the one that was sent");
|
|
assert.deepEqual(sent.dragonroll.tools, ["Thieves' tools", "Dice set"]);
|
|
assert.deepEqual(sent.dragonroll.languages, ["Common", "Deep Speech"]);
|
|
});
|
|
|
|
test("an actor listing no tools or languages says nothing about them", async () => {
|
|
const actor = makeStubActor("actor-1", "Grunt", { details: { level: 1 } });
|
|
|
|
const sent = await pushAfterEdit(actor, { config: { DND5E: { tools: { thieves: { label: "Thieves' tools" } } } } });
|
|
|
|
assert.equal(sent.dragonroll, undefined, "no dragonroll block is what tells the campaign nothing was said");
|
|
});
|
|
|
|
// --- Every locale says it ------------------------------------------------------
|
|
|
|
test("every locale names the skills, the saving throws, the tools, the languages and the coins", () => {
|
|
for (const locale of ["en", "es", "ca"]) {
|
|
const sheet = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"))["character-sheet"];
|
|
for (const key of ["skills", "saving-throws", "tools", "languages", "currency", "item-icon"]) {
|
|
assert.ok(sheet[key], `${locale} is missing campaigns.character-sheet.${key}`);
|
|
}
|
|
for (const [group, keys] of [["abilities", ["str", "dex", "con", "int", "wis", "cha"]], ["skill-names", skillKeys], ["currency-units", currencyUnits]]) {
|
|
for (const key of keys) {
|
|
assert.ok(sheet[group]?.[key], `${locale} is missing campaigns.character-sheet.${group}.${key}`);
|
|
}
|
|
}
|
|
assert.deepEqual(Object.keys(sheet["skill-names"]).sort(), [...skillKeys].sort(), `${locale} names every skill the sheet lists`);
|
|
assert.notEqual(sheet["skill-names"].acrobatics, "acrobatics", `${locale} spells the skill out, not its key`);
|
|
}
|
|
});
|