Compare commits

...

11 Commits

Author SHA1 Message Date
Bertie690
f9c11448a7
Merge 59f9c3e68d into f42237d415 2025-08-14 13:28:35 -04:00
Bertie690
f42237d415
[Refactor] Removed map(x => x) (#6256)
* Enforced a few usages of `toCamelCase`

* Removed `map(x => x)`

* Removed more maps and sufff

* Update test/mystery-encounter/encounters/weird-dream-encounter.test.ts

* Update game-data.ts types to work
2025-08-14 10:25:44 -07:00
fabske0
b44f0a4176
[Refactor] Remove bgm param from arena constructor (#6254) 2025-08-14 16:52:56 +00:00
Bertie690
59f9c3e68d
Update vitest.setup.ts
Co-authored-by: NightKev <34855794+DayKev@users.noreply.github.com>
2025-08-05 00:00:34 -04:00
NightKev
8f9edf38e8
Merge branch 'beta' into mock-console-log 2025-08-04 20:59:02 -07:00
NightKev
0d0f8e3be3
Remove redundant comment 2025-08-04 20:58:23 -07:00
NightKev
938a4cf451
Fix typo 2025-08-04 20:58:11 -07:00
NightKev
989cfbc223 Fix Focus Punch test 2025-08-04 20:56:59 -07:00
Bertie690
63da1126a7 Added minor comment 2025-08-04 23:16:01 -04:00
Bertie690
b5b44ea0b1 Cleaned up handling of colors and such 2025-08-04 23:04:40 -04:00
Bertie690
56b5461c95 Added mock console and fixed up many many things 2025-08-04 19:03:00 -04:00
26 changed files with 542 additions and 245 deletions

View File

@ -104,6 +104,7 @@ import {
getLuckString, getLuckString,
getLuckTextTint, getLuckTextTint,
getPartyLuckValue, getPartyLuckValue,
type ModifierType,
PokemonHeldItemModifierType, PokemonHeldItemModifierType,
} from "#modifiers/modifier-type"; } from "#modifiers/modifier-type";
import { MysteryEncounter } from "#mystery-encounters/mystery-encounter"; import { MysteryEncounter } from "#mystery-encounters/mystery-encounter";
@ -1203,7 +1204,9 @@ export class BattleScene extends SceneBase {
this.updateScoreText(); this.updateScoreText();
this.scoreText.setVisible(false); this.scoreText.setVisible(false);
[this.luckLabelText, this.luckText].map(t => t.setVisible(false)); [this.luckLabelText, this.luckText].forEach(t => {
t.setVisible(false);
});
this.newArena(Overrides.STARTING_BIOME_OVERRIDE || BiomeId.TOWN); this.newArena(Overrides.STARTING_BIOME_OVERRIDE || BiomeId.TOWN);
@ -1237,8 +1240,7 @@ export class BattleScene extends SceneBase {
Object.values(mp) Object.values(mp)
.flat() .flat()
.map(mt => mt.modifierType) .map(mt => mt.modifierType)
.filter(mt => "localize" in mt) .filter((mt): mt is ModifierType & Localizable => "localize" in mt && typeof mt.localize === "function"),
.map(lpb => lpb as unknown as Localizable),
), ),
]; ];
for (const item of localizable) { for (const item of localizable) {
@ -1513,8 +1515,8 @@ export class BattleScene extends SceneBase {
return this.currentBattle; return this.currentBattle;
} }
newArena(biome: BiomeId, playerFaints?: number): Arena { newArena(biome: BiomeId, playerFaints = 0): Arena {
this.arena = new Arena(biome, BiomeId[biome].toLowerCase(), playerFaints); this.arena = new Arena(biome, playerFaints);
this.eventTarget.dispatchEvent(new NewArenaEvent()); this.eventTarget.dispatchEvent(new NewArenaEvent());
this.arenaBg.pipelineData = { this.arenaBg.pipelineData = {
@ -2711,7 +2713,9 @@ export class BattleScene extends SceneBase {
} }
} }
this.party.map(p => p.updateInfo(instant)); this.party.forEach(p => {
p.updateInfo(instant);
});
} else { } else {
const args = [this]; const args = [this];
if (modifier.shouldApply(...args)) { if (modifier.shouldApply(...args)) {

View File

@ -74,6 +74,7 @@ import {
randSeedItem, randSeedItem,
toDmgValue, toDmgValue,
} from "#utils/common"; } from "#utils/common";
import { toCamelCase } from "#utils/strings";
import i18next from "i18next"; import i18next from "i18next";
export class Ability implements Localizable { export class Ability implements Localizable {
@ -109,13 +110,9 @@ export class Ability implements Localizable {
} }
localize(): void { localize(): void {
const i18nKey = AbilityId[this.id] const i18nKey = toCamelCase(AbilityId[this.id]);
.split("_")
.filter(f => f)
.map((f, i) => (i ? `${f[0]}${f.slice(1).toLowerCase()}` : f.toLowerCase()))
.join("") as string;
this.name = this.id ? `${i18next.t(`ability:${i18nKey}.name`) as string}${this.nameAppend}` : ""; this.name = this.id ? `${i18next.t(`ability:${i18nKey}.name`)}${this.nameAppend}` : "";
this.description = this.id ? (i18next.t(`ability:${i18nKey}.description`) as string) : ""; this.description = this.id ? (i18next.t(`ability:${i18nKey}.description`) as string) : "";
} }

View File

@ -1866,17 +1866,16 @@ interface PokemonPrevolutions {
export const pokemonPrevolutions: PokemonPrevolutions = {}; export const pokemonPrevolutions: PokemonPrevolutions = {};
export function initPokemonPrevolutions(): void { export function initPokemonPrevolutions(): void {
const megaFormKeys = [ SpeciesFormKey.MEGA, "", SpeciesFormKey.MEGA_X, "", SpeciesFormKey.MEGA_Y ].map(sfk => sfk as string); // TODO: Why do we have empty strings in our array?
const prevolutionKeys = Object.keys(pokemonEvolutions); const megaFormKeys = [ SpeciesFormKey.MEGA, "", SpeciesFormKey.MEGA_X, "", SpeciesFormKey.MEGA_Y ];
prevolutionKeys.forEach(pk => { for (const [pk, evolutions] of Object.entries(pokemonEvolutions)) {
const evolutions = pokemonEvolutions[pk];
for (const ev of evolutions) { for (const ev of evolutions) {
if (ev.evoFormKey && megaFormKeys.indexOf(ev.evoFormKey) > -1) { if (ev.evoFormKey && megaFormKeys.indexOf(ev.evoFormKey) > -1) {
continue; continue;
} }
pokemonPrevolutions[ev.speciesId] = Number.parseInt(pk) as SpeciesId; pokemonPrevolutions[ev.speciesId] = Number.parseInt(pk) as SpeciesId;
} }
}); }
} }

View File

@ -90,7 +90,7 @@ import type { ChargingMove, MoveAttrMap, MoveAttrString, MoveClassMap, MoveKindS
import type { TurnMove } from "#types/turn-move"; import type { TurnMove } from "#types/turn-move";
import { BooleanHolder, type Constructor, isNullOrUndefined, NumberHolder, randSeedFloat, randSeedInt, randSeedItem, toDmgValue } from "#utils/common"; import { BooleanHolder, type Constructor, isNullOrUndefined, NumberHolder, randSeedFloat, randSeedInt, randSeedItem, toDmgValue } from "#utils/common";
import { getEnumValues } from "#utils/enums"; import { getEnumValues } from "#utils/enums";
import { toTitleCase } from "#utils/strings"; import { toCamelCase, toTitleCase } from "#utils/strings";
import i18next from "i18next"; import i18next from "i18next";
import { applyChallenges } from "#utils/challenge-utils"; import { applyChallenges } from "#utils/challenge-utils";
@ -162,10 +162,16 @@ export abstract class Move implements Localizable {
} }
localize(): void { localize(): void {
const i18nKey = MoveId[this.id].split("_").filter(f => f).map((f, i) => i ? `${f[0]}${f.slice(1).toLowerCase()}` : f.toLowerCase()).join("") as unknown as string; const i18nKey = toCamelCase(MoveId[this.id])
this.name = this.id ? `${i18next.t(`move:${i18nKey}.name`)}${this.nameAppend}` : ""; if (this.id === MoveId.NONE) {
this.effect = this.id ? `${i18next.t(`move:${i18nKey}.effect`)}${this.nameAppend}` : ""; this.name = "";
this.effect = ""
return;
}
this.name = `${i18next.t(`move:${i18nKey}.name`)}${this.nameAppend}`;
this.effect = `${i18next.t(`move:${i18nKey}.effect`)}${this.nameAppend}`;
} }
/** /**
@ -5926,8 +5932,8 @@ export class ProtectAttr extends AddBattlerTagAttr {
for (const turnMove of user.getLastXMoves(-1).slice()) { for (const turnMove of user.getLastXMoves(-1).slice()) {
if ( if (
// Quick & Wide guard increment the Protect counter without using it for fail chance // Quick & Wide guard increment the Protect counter without using it for fail chance
!(allMoves[turnMove.move].hasAttr("ProtectAttr") || !(allMoves[turnMove.move].hasAttr("ProtectAttr") ||
[MoveId.QUICK_GUARD, MoveId.WIDE_GUARD].includes(turnMove.move)) || [MoveId.QUICK_GUARD, MoveId.WIDE_GUARD].includes(turnMove.move)) ||
turnMove.result !== MoveResult.SUCCESS turnMove.result !== MoveResult.SUCCESS
) { ) {
break; break;

View File

@ -12,6 +12,7 @@ import { WeatherType } from "#enums/weather-type";
import type { Pokemon } from "#field/pokemon"; import type { Pokemon } from "#field/pokemon";
import type { PokemonFormChangeItemModifier } from "#modifiers/modifier"; import type { PokemonFormChangeItemModifier } from "#modifiers/modifier";
import { type Constructor, coerceArray } from "#utils/common"; import { type Constructor, coerceArray } from "#utils/common";
import { toCamelCase } from "#utils/strings";
import i18next from "i18next"; import i18next from "i18next";
export abstract class SpeciesFormChangeTrigger { export abstract class SpeciesFormChangeTrigger {
@ -143,11 +144,7 @@ export class SpeciesFormChangeMoveLearnedTrigger extends SpeciesFormChangeTrigge
super(); super();
this.move = move; this.move = move;
this.known = known; this.known = known;
const moveKey = MoveId[this.move] const moveKey = toCamelCase(MoveId[this.move]);
.split("_")
.filter(f => f)
.map((f, i) => (i ? `${f[0]}${f.slice(1).toLowerCase()}` : f.toLowerCase()))
.join("") as unknown as string;
this.description = known this.description = known
? i18next.t("pokemonEvolutions:Forms.moveLearned", { ? i18next.t("pokemonEvolutions:Forms.moveLearned", {
move: i18next.t(`move:${moveKey}.name`), move: i18next.t(`move:${moveKey}.name`),

View File

@ -54,7 +54,7 @@ export class Arena {
public bgm: string; public bgm: string;
public ignoreAbilities: boolean; public ignoreAbilities: boolean;
public ignoringEffectSource: BattlerIndex | null; public ignoringEffectSource: BattlerIndex | null;
public playerTerasUsed: number; public playerTerasUsed = 0;
/** /**
* Saves the number of times a party pokemon faints during a arena encounter. * Saves the number of times a party pokemon faints during a arena encounter.
* {@linkcode globalScene.currentBattle.enemyFaints} is the corresponding faint counter for the enemy (this resets every wave). * {@linkcode globalScene.currentBattle.enemyFaints} is the corresponding faint counter for the enemy (this resets every wave).
@ -68,12 +68,11 @@ export class Arena {
public readonly eventTarget: EventTarget = new EventTarget(); public readonly eventTarget: EventTarget = new EventTarget();
constructor(biome: BiomeId, bgm: string, playerFaints = 0) { constructor(biome: BiomeId, playerFaints = 0) {
this.biomeType = biome; this.biomeType = biome;
this.bgm = bgm; this.bgm = BiomeId[biome].toLowerCase();
this.trainerPool = biomeTrainerPools[biome]; this.trainerPool = biomeTrainerPools[biome];
this.updatePoolsForTimeOfDay(); this.updatePoolsForTimeOfDay();
this.playerTerasUsed = 0;
this.playerFaints = playerFaints; this.playerFaints = playerFaints;
} }

View File

@ -4,6 +4,7 @@ import { initEggMoves } from "#balance/egg-moves";
import { initPokemonPrevolutions, initPokemonStarters } from "#balance/pokemon-evolutions"; import { initPokemonPrevolutions, initPokemonStarters } from "#balance/pokemon-evolutions";
import { initSpecies } from "#balance/pokemon-species"; import { initSpecies } from "#balance/pokemon-species";
import { initChallenges } from "#data/challenge"; import { initChallenges } from "#data/challenge";
import { allMoves } from "#data/data-lists";
import { initTrainerTypeDialogue } from "#data/dialogue"; import { initTrainerTypeDialogue } from "#data/dialogue";
import { initPokemonForms } from "#data/pokemon-forms"; import { initPokemonForms } from "#data/pokemon-forms";
import { initModifierPools } from "#modifiers/init-modifier-pools"; import { initModifierPools } from "#modifiers/init-modifier-pools";
@ -16,6 +17,9 @@ import { initStatsKeys } from "#ui/game-stats-ui-handler";
/** Initialize the game. */ /** Initialize the game. */
export function initializeGame() { export function initializeGame() {
if (allMoves.length > 0) {
return;
}
initModifierTypes(); initModifierTypes();
initModifierPools(); initModifierPools();
initAchievements(); initAchievements();

View File

@ -447,7 +447,9 @@ export class LoadingScene extends SceneBase {
); );
if (!mobile) { if (!mobile) {
loadingGraphics.map(g => g.setVisible(false)); loadingGraphics.forEach(g => {
g.setVisible(false);
});
} }
const intro = this.add.video(0, 0); const intro = this.add.video(0, 0);

View File

@ -121,8 +121,8 @@ export class ModifierBar extends Phaser.GameObjects.Container {
} }
updateModifierOverflowVisibility(ignoreLimit: boolean) { updateModifierOverflowVisibility(ignoreLimit: boolean) {
const modifierIcons = this.getAll().reverse(); const modifierIcons = this.getAll().reverse() as Phaser.GameObjects.Container[];
for (const modifier of modifierIcons.map(m => m as Phaser.GameObjects.Container).slice(iconOverflowIndex)) { for (const modifier of modifierIcons.slice(iconOverflowIndex)) {
modifier.setVisible(ignoreLimit); modifier.setVisible(ignoreLimit);
} }
} }

View File

@ -118,7 +118,10 @@ export class MovePhase extends BattlePhase {
public start(): void { public start(): void {
super.start(); super.start();
console.log(MoveId[this.move.moveId], enumValueToKey(MoveUseMode, this.useMode)); console.log(
`%cMove: ${MoveId[this.move.moveId]}; Use Mode: ${enumValueToKey(MoveUseMode, this.useMode)}`,
"color:RebeccaPurple",
);
// Check if move is unusable (e.g. running out of PP due to a mid-turn Spite // Check if move is unusable (e.g. running out of PP due to a mid-turn Spite
// or the user no longer being on field), ending the phase early if not. // or the user no longer being on field), ending the phase early if not.

View File

@ -207,10 +207,12 @@ export interface StarterData {
[key: number]: StarterDataEntry; [key: number]: StarterDataEntry;
} }
export interface TutorialFlags { // TODO: Rework into a bitmask
[key: string]: boolean; export type TutorialFlags = {
} [key in Tutorial]: boolean;
};
// TODO: Rework into a bitmask
export interface SeenDialogues { export interface SeenDialogues {
[key: string]: boolean; [key: string]: boolean;
} }
@ -823,52 +825,51 @@ export class GameData {
return true; // TODO: is `true` the correct return value? return true; // TODO: is `true` the correct return value?
} }
private loadGamepadSettings(): boolean { private loadGamepadSettings(): void {
Object.values(SettingGamepad) Object.values(SettingGamepad).forEach(setting => {
.map(setting => setting as SettingGamepad) setSettingGamepad(setting, settingGamepadDefaults[setting]);
.forEach(setting => setSettingGamepad(setting, settingGamepadDefaults[setting])); });
if (!localStorage.hasOwnProperty("settingsGamepad")) { if (!localStorage.hasOwnProperty("settingsGamepad")) {
return false; return;
} }
const settingsGamepad = JSON.parse(localStorage.getItem("settingsGamepad")!); // TODO: is this bang correct? const settingsGamepad = JSON.parse(localStorage.getItem("settingsGamepad")!); // TODO: is this bang correct?
for (const setting of Object.keys(settingsGamepad)) { for (const setting of Object.keys(settingsGamepad)) {
setSettingGamepad(setting as SettingGamepad, settingsGamepad[setting]); setSettingGamepad(setting as SettingGamepad, settingsGamepad[setting]);
} }
return true; // TODO: is `true` the correct return value?
} }
public saveTutorialFlag(tutorial: Tutorial, flag: boolean): boolean { /**
const key = getDataTypeKey(GameDataType.TUTORIALS); * Save the specified tutorial as having the specified completion status.
let tutorials: object = {}; * @param tutorial - The {@linkcode Tutorial} whose completion status is being saved
if (localStorage.hasOwnProperty(key)) { * @param status - The completion status to set
tutorials = JSON.parse(localStorage.getItem(key)!); // TODO: is this bang correct? */
public saveTutorialFlag(tutorial: Tutorial, status: boolean): void {
// Grab the prior save data tutorial
const saveDataKey = getDataTypeKey(GameDataType.TUTORIALS);
const tutorials: TutorialFlags = localStorage.hasOwnProperty(saveDataKey)
? JSON.parse(localStorage.getItem(saveDataKey)!)
: {};
// TODO: We shouldn't be storing this like that
for (const key of Object.values(Tutorial)) {
if (key === tutorial) {
tutorials[key] = status;
} else {
tutorials[key] ??= false;
}
} }
Object.keys(Tutorial) localStorage.setItem(saveDataKey, JSON.stringify(tutorials));
.map(t => t as Tutorial)
.forEach(t => {
const key = Tutorial[t];
if (key === tutorial) {
tutorials[key] = flag;
} else {
tutorials[key] ??= false;
}
});
localStorage.setItem(key, JSON.stringify(tutorials));
return true;
} }
public getTutorialFlags(): TutorialFlags { public getTutorialFlags(): TutorialFlags {
const key = getDataTypeKey(GameDataType.TUTORIALS); const key = getDataTypeKey(GameDataType.TUTORIALS);
const ret: TutorialFlags = {}; const ret: TutorialFlags = Object.values(Tutorial).reduce((acc, tutorial) => {
Object.values(Tutorial) acc[Tutorial[tutorial]] = false;
.map(tutorial => tutorial as Tutorial) return acc;
.forEach(tutorial => (ret[Tutorial[tutorial]] = false)); }, {} as TutorialFlags);
if (!localStorage.hasOwnProperty(key)) { if (!localStorage.hasOwnProperty(key)) {
return ret; return ret;

View File

@ -26,6 +26,7 @@ import { addBBCodeTextObject, addTextObject, getTextColor } from "#ui/text";
import { UiHandler } from "#ui/ui-handler"; import { UiHandler } from "#ui/ui-handler";
import { addWindow } from "#ui/ui-theme"; import { addWindow } from "#ui/ui-theme";
import { formatFancyLargeNumber, formatLargeNumber, formatMoney, getPlayTimeString } from "#utils/common"; import { formatFancyLargeNumber, formatLargeNumber, formatMoney, getPlayTimeString } from "#utils/common";
import { toCamelCase } from "#utils/strings";
import i18next from "i18next"; import i18next from "i18next";
import RoundRectangle from "phaser3-rex-plugins/plugins/roundrectangle"; import RoundRectangle from "phaser3-rex-plugins/plugins/roundrectangle";
@ -706,10 +707,7 @@ export class RunInfoUiHandler extends UiHandler {
rules.push(i18next.t("challenges:inverseBattle.shortName")); rules.push(i18next.t("challenges:inverseBattle.shortName"));
break; break;
default: { default: {
const localizationKey = Challenges[this.runInfo.challenges[i].id] const localizationKey = toCamelCase(Challenges[this.runInfo.challenges[i].id]);
.split("_")
.map((f, i) => (i ? `${f[0]}${f.slice(1).toLowerCase()}` : f.toLowerCase()))
.join("");
rules.push(i18next.t(`challenges:${localizationKey}.name`)); rules.push(i18next.t(`challenges:${localizationKey}.name`));
break; break;
} }

View File

@ -31,7 +31,7 @@ export class TestDialogueUiHandler extends FormModalUiHandler {
// we check for null or undefined here as per above - the typeof is still an object but the value is null so we need to exit out of this and pass the null key // we check for null or undefined here as per above - the typeof is still an object but the value is null so we need to exit out of this and pass the null key
// Return in the format expected by i18next // Return in the format expected by i18next
return middleKey ? `${topKey}:${middleKey.map(m => m).join(".")}.${t}` : `${topKey}:${t}`; return middleKey ? `${topKey}:${middleKey.join(".")}.${t}` : `${topKey}:${t}`;
} }
}) })
.filter(t => t); .filter(t => t);

View File

@ -99,7 +99,7 @@ describe("Abilities - Cud Chew", () => {
expect(abDisplaySpy.mock.calls[1][2]).toBe(false); expect(abDisplaySpy.mock.calls[1][2]).toBe(false);
// should display messgae // should display messgae
expect(game.textInterceptor.getLatestMessage()).toBe( expect(game.textInterceptor.logs).toContain(
i18next.t("battle:hpIsFull", { i18next.t("battle:hpIsFull", {
pokemonName: getPokemonNameWithAffix(farigiraf), pokemonName: getPokemonNameWithAffix(farigiraf),
}), }),

View File

@ -9,7 +9,7 @@ import { TurnStartPhase } from "#phases/turn-start-phase";
import { GameManager } from "#test/test-utils/game-manager"; import { GameManager } from "#test/test-utils/game-manager";
import i18next from "i18next"; import i18next from "i18next";
import Phaser from "phaser"; import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Moves - Focus Punch", () => { describe("Moves - Focus Punch", () => {
let phaserGame: Phaser.Game; let phaserGame: Phaser.Game;
@ -125,8 +125,8 @@ describe("Moves - Focus Punch", () => {
game.move.select(MoveId.FOCUS_PUNCH); game.move.select(MoveId.FOCUS_PUNCH);
await game.phaseInterceptor.to("MoveEndPhase", true); await game.phaseInterceptor.to("MoveEndPhase", true);
await game.phaseInterceptor.to("MessagePhase", false); await game.phaseInterceptor.to("MessagePhase", false);
const consoleSpy = vi.spyOn(console, "log");
await game.phaseInterceptor.to("MoveEndPhase", true); await game.phaseInterceptor.to("MoveEndPhase", true);
expect(consoleSpy).nthCalledWith(1, i18next.t("moveTriggers:lostFocus", { pokemonName: "Charizard" })); expect(game.textInterceptor.logs).toContain(i18next.t("moveTriggers:lostFocus", { pokemonName: "Charizard" }));
expect(game.textInterceptor.logs).not.toContain(i18next.t("battle:attackFailed"));
}); });
}); });

View File

@ -112,7 +112,7 @@ describe("Weird Dream - Mystery Encounter", () => {
it("should transform the new party into new species, 2 at +90/+110, the rest at +40/50 BST", async () => { it("should transform the new party into new species, 2 at +90/+110, the rest at +40/50 BST", async () => {
await game.runToMysteryEncounter(MysteryEncounterType.WEIRD_DREAM, defaultParty); await game.runToMysteryEncounter(MysteryEncounterType.WEIRD_DREAM, defaultParty);
const pokemonPrior = scene.getPlayerParty().map(pokemon => pokemon); const pokemonPrior = scene.getPlayerParty().slice();
const bstsPrior = pokemonPrior.map(species => species.getSpeciesForm().getBaseStatTotal()); const bstsPrior = pokemonPrior.map(species => species.getSpeciesForm().getBaseStatTotal());
await runMysteryEncounterToEnd(game, 1); await runMysteryEncounterToEnd(game, 1);

View File

@ -6,17 +6,13 @@ import * as bypassLoginModule from "#app/global-vars/bypass-login";
import { MoveAnim } from "#data/battle-anims"; import { MoveAnim } from "#data/battle-anims";
import { Pokemon } from "#field/pokemon"; import { Pokemon } from "#field/pokemon";
import { version } from "#package.json"; import { version } from "#package.json";
import { blobToString } from "#test/test-utils/game-manager-utils";
import { MockClock } from "#test/test-utils/mocks/mock-clock"; import { MockClock } from "#test/test-utils/mocks/mock-clock";
import { MockFetch } from "#test/test-utils/mocks/mock-fetch";
import { MockGameObjectCreator } from "#test/test-utils/mocks/mock-game-object-creator"; import { MockGameObjectCreator } from "#test/test-utils/mocks/mock-game-object-creator";
import { MockLoader } from "#test/test-utils/mocks/mock-loader"; import { MockLoader } from "#test/test-utils/mocks/mock-loader";
import { MockTextureManager } from "#test/test-utils/mocks/mock-texture-manager"; import { MockTextureManager } from "#test/test-utils/mocks/mock-texture-manager";
import { MockTimedEventManager } from "#test/test-utils/mocks/mock-timed-event-manager"; import { MockTimedEventManager } from "#test/test-utils/mocks/mock-timed-event-manager";
import { MockContainer } from "#test/test-utils/mocks/mocks-container/mock-container"; import { MockContainer } from "#test/test-utils/mocks/mocks-container/mock-container";
import { PokedexMonContainer } from "#ui/pokedex-mon-container"; import { PokedexMonContainer } from "#ui/pokedex-mon-container";
import { sessionIdKey } from "#utils/common";
import { setCookie } from "#utils/cookies";
import fs from "node:fs"; import fs from "node:fs";
import Phaser from "phaser"; import Phaser from "phaser";
import { vi } from "vitest"; import { vi } from "vitest";
@ -28,20 +24,6 @@ const GamepadPlugin = Phaser.Input.Gamepad.GamepadPlugin;
const EventEmitter = Phaser.Events.EventEmitter; const EventEmitter = Phaser.Events.EventEmitter;
const UpdateList = Phaser.GameObjects.UpdateList; const UpdateList = Phaser.GameObjects.UpdateList;
window.URL.createObjectURL = (blob: Blob) => {
blobToString(blob).then((data: string) => {
localStorage.setItem("toExport", data);
});
return null;
};
navigator.getGamepads = () => [];
global.fetch = vi.fn(MockFetch);
setCookie(sessionIdKey, "fake_token");
window.matchMedia = () => ({
matches: false,
});
export class GameWrapper { export class GameWrapper {
public game: Phaser.Game; public game: Phaser.Game;
public scene: BattleScene; public scene: BattleScene;
@ -99,6 +81,7 @@ export class GameWrapper {
removeAll: () => null, removeAll: () => null,
}; };
// TODO: Can't we just turn on `noAudio` in audio config?
this.scene.sound = { this.scene.sound = {
play: () => null, play: () => null,
pause: () => null, pause: () => null,

View File

@ -19,6 +19,7 @@ import type { ModifierOverride } from "#modifiers/modifier-type";
import type { Variant } from "#sprites/variant"; import type { Variant } from "#sprites/variant";
import { GameManagerHelper } from "#test/test-utils/helpers/game-manager-helper"; import { GameManagerHelper } from "#test/test-utils/helpers/game-manager-helper";
import { coerceArray, shiftCharCodes } from "#utils/common"; import { coerceArray, shiftCharCodes } from "#utils/common";
import chalk from "chalk";
import { vi } from "vitest"; import { vi } from "vitest";
/** /**
@ -665,6 +666,6 @@ export class OverridesHelper extends GameManagerHelper {
} }
private log(...params: any[]) { private log(...params: any[]) {
console.log("Overrides:", ...params); console.log(chalk.hex("#b0b01eff")("Overrides:", ...params));
} }
} }

View File

@ -1,80 +0,0 @@
const originalLog = console.log;
const originalError = console.error;
const originalDebug = console.debug;
const originalWarn = console.warn;
const blacklist = ["Phaser", "variant icon does not exist", 'Texture "%s" not found'];
const whitelist = ["Phase"];
export class MockConsoleLog {
constructor(
private logDisabled = false,
private phaseText = false,
) {}
private logs: any[] = [];
private notified: any[] = [];
public log(...args) {
const argsStr = this.getStr(args);
this.logs.push(argsStr);
if (this.logDisabled && !this.phaseText) {
return;
}
if ((this.phaseText && !whitelist.some(b => argsStr.includes(b))) || blacklist.some(b => argsStr.includes(b))) {
return;
}
originalLog(args);
}
public error(...args) {
const argsStr = this.getStr(args);
this.logs.push(argsStr);
originalError(args); // Appelle le console.error originel
}
public debug(...args) {
const argsStr = this.getStr(args);
this.logs.push(argsStr);
if (this.logDisabled && !this.phaseText) {
return;
}
if (!whitelist.some(b => argsStr.includes(b)) || blacklist.some(b => argsStr.includes(b))) {
return;
}
originalDebug(args);
}
warn(...args) {
const argsStr = this.getStr(args);
this.logs.push(args);
if (this.logDisabled && !this.phaseText) {
return;
}
if (!whitelist.some(b => argsStr.includes(b)) || blacklist.some(b => argsStr.includes(b))) {
return;
}
originalWarn(args);
}
notify(msg) {
originalLog(msg);
this.notified.push(msg);
}
getLogs() {
return this.logs;
}
clearLogs() {
this.logs = [];
}
getStr(...args) {
return args
.map(arg => {
if (typeof arg === "object" && arg !== null) {
// Handle objects including arrays
return JSON.stringify(arg, (_key, value) => (typeof value === "bigint" ? value.toString() : value));
}
if (typeof arg === "bigint") {
// Handle BigInt values
return arg.toString();
}
return arg.toString();
})
.join(";");
}
}

View File

@ -0,0 +1,150 @@
{
"AliceBlue": "f0f8ff",
"AntiqueWhite": "faebd7",
"Aqua": "00ffff",
"Aquamarine": "7fffd4",
"Azure": "f0ffff",
"Beige": "f5f5dc",
"Bisque": "ffe4c4",
"Black": "000000",
"BlanchedAlmond": "ffebcd",
"Blue": "0000ff",
"BlueViolet": "8a2be2",
"Brown": "a52a2a",
"BurlyWood": "deb887",
"CadetBlue": "5f9ea0",
"Chartreuse": "7fff00",
"Chocolate": "d2691e",
"Coral": "ff7f50",
"CornflowerBlue": "6495ed",
"Cornsilk": "fff8dc",
"Crimson": "dc143c",
"Cyan": "00ffff",
"DarkBlue": "00008b",
"DarkCyan": "008b8b",
"DarkGoldenRod": "b8860b",
"DarkGray": "a9a9a9",
"DarkGrey": "a9a9a9",
"DarkGreen": "006400",
"DarkKhaki": "bdb76b",
"DarkMagenta": "8b008b",
"DarkOliveGreen": "556b2f",
"DarkOrange": "ff8c00",
"DarkOrchid": "9932cc",
"DarkRed": "8b0000",
"DarkSalmon": "e9967a",
"DarkSeaGreen": "8fbc8f",
"DarkSlateBlue": "483d8b",
"DarkSlateGray": "2f4f4f",
"DarkSlateGrey": "2f4f4f",
"DarkTurquoise": "00ced1",
"DarkViolet": "9400d3",
"DeepPink": "ff1493",
"DeepSkyBlue": "00bfff",
"DimGray": "696969",
"DimGrey": "696969",
"DodgerBlue": "1e90ff",
"FireBrick": "b22222",
"FloralWhite": "fffaf0",
"ForestGreen": "228b22",
"Fuchsia": "ff00ff",
"Gainsboro": "dcdcdc",
"GhostWhite": "f8f8ff",
"Gold": "ffd700",
"GoldenRod": "daa520",
"Gray": "808080",
"Grey": "808080",
"Green": "008000",
"GreenYellow": "adff2f",
"HoneyDew": "f0fff0",
"HotPink": "ff69b4",
"IndianRed": "cd5c5c",
"Indigo": "4b0082",
"Ivory": "fffff0",
"Khaki": "f0e68c",
"Lavender": "e6e6fa",
"LavenderBlush": "fff0f5",
"LawnGreen": "7cfc00",
"LemonChiffon": "fffacd",
"LightBlue": "add8e6",
"LightCoral": "f08080",
"LightCyan": "e0ffff",
"LightGoldenRodYellow": "fafad2",
"LightGray": "d3d3d3",
"LightGrey": "d3d3d3",
"LightGreen": "90ee90",
"LightPink": "ffb6c1",
"LightSalmon": "ffa07a",
"LightSeaGreen": "20b2aa",
"LightSkyBlue": "87cefa",
"LightSlateGray": "778899",
"LightSlateGrey": "778899",
"LightSteelBlue": "b0c4de",
"LightYellow": "ffffe0",
"Lime": "00ff00",
"LimeGreen": "32cd32",
"Linen": "faf0e6",
"Magenta": "ff00ff",
"Maroon": "800000",
"MediumAquaMarine": "66cdaa",
"MediumBlue": "0000cd",
"MediumOrchid": "ba55d3",
"MediumPurple": "9370db",
"MediumSeaGreen": "3cb371",
"MediumSlateBlue": "7b68ee",
"MediumSpringGreen": "00fa9a",
"MediumTurquoise": "48d1cc",
"MediumVioletRed": "c71585",
"MidnightBlue": "191970",
"MintCream": "f5fffa",
"MistyRose": "ffe4e1",
"Moccasin": "ffe4b5",
"NavajoWhite": "ffdead",
"Navy": "000080",
"OldLace": "fdf5e6",
"Olive": "808000",
"OliveDrab": "6b8e23",
"Orange": "ffa500",
"OrangeRed": "ff4500",
"Orchid": "da70d6",
"PaleGoldenRod": "eee8aa",
"PaleGreen": "98fb98",
"PaleTurquoise": "afeeee",
"PaleVioletRed": "db7093",
"PapayaWhip": "ffefd5",
"PeachPuff": "ffdab9",
"Peru": "cd853f",
"Pink": "ffc0cb",
"Plum": "dda0dd",
"PowderBlue": "b0e0e6",
"Purple": "800080",
"RebeccaPurple": "663399",
"Red": "ff0000",
"RosyBrown": "bc8f8f",
"RoyalBlue": "4169e1",
"SaddleBrown": "8b4513",
"Salmon": "fa8072",
"SandyBrown": "f4a460",
"SeaGreen": "2e8b57",
"SeaShell": "fff5ee",
"Sienna": "a0522d",
"Silver": "c0c0c0",
"SkyBlue": "87ceeb",
"SlateBlue": "6a5acd",
"SlateGray": "708090",
"SlateGrey": "708090",
"Snow": "fffafa",
"SpringGreen": "00ff7f",
"SteelBlue": "4682b4",
"Tan": "d2b48c",
"Teal": "008080",
"Thistle": "d8bfd8",
"Tomato": "ff6347",
"Turquoise": "40e0d0",
"Violet": "ee82ee",
"Wheat": "f5deb3",
"White": "ffffff",
"WhiteSmoke": "f5f5f5",
"Yellow": "ffff00",
"YellowGreen": "9acd32"
}

View File

@ -0,0 +1,61 @@
import { hslToHex } from "#utils/common";
import chalk, { type ChalkInstance, type ForegroundColorName, foregroundColorNames } from "chalk";
import colorMap from "./color-map.json";
export function inferColorFormat(data: [string, ...unknown[]]): ChalkInstance {
// Remove all CSS format strings and find the first one containing something vaguely resembling a color
data[0] = data[0].replaceAll("%c", "");
const args = data.slice(1).filter(t => typeof t === "string");
const color = findColorPrefix(args);
// If the color is within Chalk's native roster, use it directly.
if ((foregroundColorNames as string[]).includes(color)) {
return chalk[color as ForegroundColorName];
}
// Otherwise, coerce it to hex before feeding it in.
return getColor(color);
}
/**
* Find the first string with a "color:" CSS directive in an argument list.
* @param args - The arguments containing the color directive
* @returns The found color, or `"green"` if none were found
*/
function findColorPrefix(args: string[]): string {
for (const arg of args) {
const match = /color:\s*(.+?)(?:;|$)/g.exec(arg);
if (match === null) {
continue;
}
return match[1];
}
return "green";
}
/**
* Coerce an arbitrary CSS color string to a Chalk instance.
* @param color - The color to coerce
* @returns The Chalk color equivalent.
*/
function getColor(color: string): ChalkInstance {
if (/^#([a-z0-9]{3,4}|[a-z0-9]{6}|[a-z0-9]{8})$/i.test(color)) {
// already in hex
return chalk.hex(color);
}
const rgbMatch = /^rgba?\((\d{1,3})%?,\s*(\d{1,3})%?,?\s*(\d{1,3})%?,\s*/i.exec(color);
if (rgbMatch) {
const [red, green, blue] = rgbMatch;
return chalk.rgb(+red, +green, +blue);
}
const hslMatch = /^hslv?\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/i.exec(color);
if (hslMatch) {
const [hue, saturation, light] = hslMatch;
return chalk.hex(hslToHex(+hue, +saturation / 100, +light / 100));
}
return chalk.hex(colorMap[color] ?? "#00ff95ff");
}

View File

@ -0,0 +1,140 @@
import { inferColorFormat } from "#test/test-utils/mocks/mock-console/infer-color";
import { coerceArray } from "#utils/common";
import { Console } from "node:console";
import { stderr, stdout } from "node:process";
import util from "node:util";
import chalk, { type ChalkInstance } from "chalk";
// Tell chalk we support truecolor
chalk.level = 3;
// TODO: Review this
const blacklist = [
"variant icon does not exist", // Repetitive warnings about icons not found
'Texture "%s" not found', // Repetitive warnings about textures not found
"type: 'Pokemon',", // Large Pokemon objects
"gameVersion: ", // Large session-data and system-data objects
"Phaser v", // Phaser version text
"Seed:", // Stuff about wave seed (we should really stop logging this shit)
"Wave Seed:", // Stuff about wave seed (we should really stop logging this shit)
];
const whitelist = ["Start Phase"];
/**
* The {@linkcode MockConsole} is a wrapper around the global {@linkcode console} object.
* It automatically colors text and such.
*/
export class MockConsole extends Console {
/**
* A list of warnings that are queued to be displayed after all tests in the same file are finished.
*/
private static queuedWarnings: unknown[][] = [];
/**
* Queue a warning to be printed after all tests in the same file are finished.
*/
// TODO: Add some warnings
public static queuePostTestWarning(...data: unknown[]): void {
MockConsole.queuedWarnings.push(data);
}
constructor() {
super(stdout, stderr, false);
}
/**
* Print all post-test warnings that have been queued, and then clears the queue.
*/
public static printPostTestWarnings() {
for (const data of MockConsole.queuedWarnings) {
console.warn(...data);
}
MockConsole.queuedWarnings = [];
}
/**
* Check whether a given set of data is in the blacklist to be barred from logging.
* @param data - The data being logged
* @returns Whether `data` is blacklisted from console logging
*/
private checkBlacklist(data: unknown[]): boolean {
const dataStr = this.getStr(data);
return !whitelist.some(b => dataStr.includes(b)) && blacklist.some(b => dataStr.includes(b));
}
public trace(...data: unknown[]) {
if (this.checkBlacklist(data)) {
return;
}
// TODO: Figure out how to add color to the full trace text
super.trace(...this.format(chalk.hex("#b700ff"), data));
}
public debug(...data: unknown[]) {
if (this.checkBlacklist(data)) {
return;
}
super.debug(...this.format(chalk.hex("#874600ff"), data));
}
public log(...data: unknown[]): void {
if (this.checkBlacklist(data)) {
return;
}
let formatter: ChalkInstance | undefined;
if (data.some(d => typeof d === "string" && d.includes("color:"))) {
// Infer the color format from the arguments, then remove everything but the message.
formatter = inferColorFormat(data as [string, ...unknown[]]);
data.splice(1);
} else if (data[0] === "[UI]") {
// Cyan for UI debug messages
formatter = chalk.hex("#009dffff");
} else if (typeof data[0] === "string" && data[0].startsWith("=====")) {
// Orange logging for "New Turn"/etc messages
formatter = chalk.hex("#ffad00ff");
}
super.log(...this.format(formatter, data));
}
public warn(...data: unknown[]) {
if (this.checkBlacklist(data)) {
return;
}
super.warn(...this.format(chalk.yellow, data));
}
public error(...data: unknown[]) {
if (this.checkBlacklist(data)) {
return;
}
super.error(...this.format(chalk.redBright, data));
}
/**
* Returns a human-readable string representation of `data`.
*/
private getStr(data: unknown) {
return util.inspect(data, { sorted: true, breakLength: 120 });
}
/**
* Stringify the given data in a manner fit for logging.
* @param color - A Chalk instance or other transformation function used to transform the output,
* or `undefined` to not transform it at all.
* @param data - The data that the format should be applied to.
* @returns A stringified copy of `data` with {@linkcode color} applied to each individual argument.
* @todo Do we need to apply color to each entry or just run it through `util.format`?
*/
private format(color: ((s: unknown) => unknown) | undefined, data: unknown | unknown[]): unknown[] {
data = coerceArray(data);
color ??= a => a;
return (data as unknown[]).map(a => color(typeof a === "function" || typeof a === "object" ? this.getStr(a) : a));
}
}

View File

@ -1,4 +1,5 @@
import type { MockGameObject } from "#test/test-utils/mocks/mock-game-object"; import type { MockGameObject } from "#test/test-utils/mocks/mock-game-object";
import type { TextInterceptor } from "#test/test-utils/text-interceptor";
import { UI } from "#ui/ui"; import { UI } from "#ui/ui";
export class MockText implements MockGameObject { export class MockText implements MockGameObject {
@ -82,13 +83,14 @@ export class MockText implements MockGameObject {
showText( showText(
text: string, text: string,
delay?: number | null, _delay?: number | null,
callback?: Function | null, callback?: Function | null,
callbackDelay?: number | null, _callbackDelay?: number | null,
prompt?: boolean | null, _prompt?: boolean | null,
promptDelay?: number | null, _promptDelay?: number | null,
) { ) {
this.scene.messageWrapper.showText(text, delay, callback, callbackDelay, prompt, promptDelay); // TODO: this is a very bad way to pass calls around
(this.scene.messageWrapper as TextInterceptor).showText(text);
if (callback) { if (callback) {
callback(); callback();
} }
@ -96,13 +98,13 @@ export class MockText implements MockGameObject {
showDialogue( showDialogue(
keyOrText: string, keyOrText: string,
name: string | undefined, name: string,
delay: number | null = 0, _delay: number | null,
callback: Function, callback: Function,
callbackDelay?: number, _callbackDelay?: number,
promptDelay?: number, _promptDelay?: number,
) { ) {
this.scene.messageWrapper.showDialogue(keyOrText, name, delay, callback, callbackDelay, promptDelay); (this.scene.messageWrapper as TextInterceptor).showDialogue(keyOrText, name);
if (callback) { if (callback) {
callback(); callback();
} }

View File

@ -1,9 +1,7 @@
import { SESSION_ID_COOKIE_NAME } from "#app/constants"; import { SESSION_ID_COOKIE_NAME } from "#app/constants";
import { initializeGame } from "#app/init/init";
import { initI18n } from "#plugins/i18n";
import { blobToString } from "#test/test-utils/game-manager-utils"; import { blobToString } from "#test/test-utils/game-manager-utils";
import { manageListeners } from "#test/test-utils/listeners-manager"; import { manageListeners } from "#test/test-utils/listeners-manager";
import { MockConsoleLog } from "#test/test-utils/mocks/mock-console-log"; import { MockConsole } from "#test/test-utils/mocks/mock-console/mock-console";
import { mockContext } from "#test/test-utils/mocks/mock-context-canvas"; import { mockContext } from "#test/test-utils/mocks/mock-context-canvas";
import { mockLocalStorage } from "#test/test-utils/mocks/mock-local-storage"; import { mockLocalStorage } from "#test/test-utils/mocks/mock-local-storage";
import { MockImage } from "#test/test-utils/mocks/mocks-container/mock-image"; import { MockImage } from "#test/test-utils/mocks/mocks-container/mock-image";
@ -12,40 +10,35 @@ import Phaser from "phaser";
import BBCodeText from "phaser3-rex-plugins/plugins/bbcodetext"; import BBCodeText from "phaser3-rex-plugins/plugins/bbcodetext";
import InputText from "phaser3-rex-plugins/plugins/inputtext"; import InputText from "phaser3-rex-plugins/plugins/inputtext";
let wasInitialized = false;
/** /**
* Run initialization code upon starting a new file, both per-suite and per-instance oncess. * Run per-suite initialization code upon starting a new file.
*/ */
export function initTests(): void { export function initTests(): void {
setupStubs(); setupStubs();
if (!wasInitialized) {
initTestFile();
wasInitialized = true;
}
manageListeners(); manageListeners();
} }
/**
* Initialize various values at the beginning of each testing instance.
*/
function initTestFile(): void {
initI18n();
initializeGame();
}
/** /**
* Setup various stubs for testing. * Setup various stubs for testing.
* @todo Move this into a dedicated stub file instead of running it once per test instance * @todo Move this into a dedicated stub file instead of running it once per test instance
* @todo review these to see which are actually necessary
* @todo Investigate why this resets on new test suite start * @todo Investigate why this resets on new test suite start
*/ */
function setupStubs(): void { function setupStubs(): void {
Object.defineProperty(window, "localStorage", { console.log(console instanceof MockConsole);
value: mockLocalStorage(), console.log(Phaser.GameObjects.Image instanceof MockImage);
}); Object.defineProperties(global, {
Object.defineProperty(window, "console", { localStorage: {
value: new MockConsoleLog(false), value: mockLocalStorage(),
},
console: {
value: new MockConsole(),
},
matchMedia: {
value: () => ({
matches: false,
}),
},
}); });
Object.defineProperty(document, "fonts", { Object.defineProperty(document, "fonts", {
writable: true, writable: true,
@ -69,11 +62,6 @@ function setupStubs(): void {
navigator.getGamepads = () => []; navigator.getGamepads = () => [];
setCookie(SESSION_ID_COOKIE_NAME, "fake_token"); setCookie(SESSION_ID_COOKIE_NAME, "fake_token");
window.matchMedia = () =>
({
matches: false,
}) as any;
/** /**
* Sets this object's position relative to another object with a given offset * Sets this object's position relative to another object with a given offset
* @param guideObject - The {@linkcode Phaser.GameObjects.GameObject} to base the position off of * @param guideObject - The {@linkcode Phaser.GameObjects.GameObject} to base the position off of

View File

@ -1,39 +1,49 @@
import type { BattleScene } from "#app/battle-scene";
import chalk from "chalk";
/** /**
* Class will intercept any text or dialogue message calls and log them for test purposes * The {@linkcode TextInterceptor} is a wrapper class that intercepts and logs any messages
* that would be displayed on-screen.
*/ */
export class TextInterceptor { export class TextInterceptor {
private scene; /** A log containing messages having been displayed on screen, sorted in FIFO order. */
public logs: string[] = []; public readonly logs: string[] = [];
constructor(scene) {
this.scene = scene; constructor(scene: BattleScene) {
// @ts-expect-error: Find another more sanitary way of doing this
scene.messageWrapper = this; scene.messageWrapper = this;
} }
showText( /** Clear the current content of the TextInterceptor. */
text: string, public clearLogs(): void {
_delay?: number, this.logs.splice(0);
_callback?: Function, }
_callbackDelay?: number,
_prompt?: boolean, showText(text: string): void {
_promptDelay?: number, // NB: We do not format the raw _logs_ themselves as tests will be actively checking it.
): void { console.log(this.formatText(text));
console.log(text);
this.logs.push(text); this.logs.push(text);
} }
showDialogue( showDialogue(text: string, name: string): void {
text: string, console.log(`${name}: \n${this.formatText(text)}`);
name: string,
_delay?: number,
_callback?: Function,
_callbackDelay?: number,
_promptDelay?: number,
): void {
console.log(name, text);
this.logs.push(name, text); this.logs.push(name, text);
} }
getLatestMessage(): string { /**
return this.logs.pop() ?? ""; * Format text to be displayed to the test console, as follows:
* 1. Replaces new lines and new text boxes (marked by `$`) with indented new lines.
* 2. Removes all `@c{}`, `@d{}`, `@s{}`, and `@f{}` flags from the text.
* 3. Makes text blue
* @param text - The unformatted text
* @returns The formatted text
*/
private formatText(text: string): string {
return chalk.blue(
text
.replace(/\n/g, " ")
.replace(/\$/g, "\n ")
.replace(/@\w{.*?}/g, ""),
);
} }
} }

View File

@ -1,5 +1,8 @@
import "vitest-canvas-mock"; import "vitest-canvas-mock";
import { initializeGame } from "#app/init/init";
import { MockConsole } from "#test/test-utils/mocks/mock-console/mock-console";
import { initTests } from "#test/test-utils/test-file-initialization"; import { initTests } from "#test/test-utils/test-file-initialization";
import chalk from "chalk";
import { afterAll, beforeAll, vi } from "vitest"; import { afterAll, beforeAll, vi } from "vitest";
/** Set the timezone to UTC for tests. */ /** Set the timezone to UTC for tests. */
@ -14,6 +17,20 @@ vi.mock("#app/overrides", async importOriginal => {
} satisfies typeof import("#app/overrides"); } satisfies typeof import("#app/overrides");
}); });
//#region Mocking
/** Mock the override import to always return default values, ignoring any custom overrides. */
vi.mock("#app/overrides", async importOriginal => {
const { defaultOverrides } = await importOriginal<typeof import("#app/overrides")>();
return {
default: defaultOverrides,
// Export `defaultOverrides` as a *copy*.
// This ensures we can easily reset `overrides` back to its default values after modifying it.
defaultOverrides: { ...defaultOverrides },
} satisfies typeof import("#app/overrides");
});
/** /**
* This is a hacky way to mock the i18n backend requests (with the help of {@link https://mswjs.io/ | msw}). * This is a hacky way to mock the i18n backend requests (with the help of {@link https://mswjs.io/ | msw}).
* The reason to put it inside of a mock is to elevate it. * The reason to put it inside of a mock is to elevate it.
@ -30,8 +47,11 @@ vi.mock("i18next", async importOriginal => {
const filename = req.params[0]; const filename = req.params[0];
try { try {
const json = await import(`../public/locales/en/${req.params[0]}`); const localeFiles = import.meta.glob("../public/locales/en/**/*.json", { eager: true });
console.log("Loaded locale", filename); const json = localeFiles[`../public/locales/en/${filename}`] || {};
if (import.meta.env.VITE_I18N_DEBUG === "1") {
console.log("Loaded locale", filename);
}
return HttpResponse.json(json); return HttpResponse.json(json);
} catch (err) { } catch (err) {
console.log(`Failed to load locale ${filename}!`, err); console.log(`Failed to load locale ${filename}!`, err);
@ -48,13 +68,25 @@ vi.mock("i18next", async importOriginal => {
return await importOriginal(); return await importOriginal();
}); });
/** Ensure that i18n is initialized on all calls. */
// TODO: Initialize i18n directly on import instead of initializing it during importing of trainer code
vi.mock("#app/plugins/i18n", async importOriginal => {
const importedStuff = await importOriginal<typeof import("#app/plugins/i18n")>();
const { initI18n } = importedStuff;
await initI18n();
return importedStuff;
});
global.testFailed = false; global.testFailed = false;
initializeGame();
beforeAll(() => { beforeAll(() => {
initTests(); initTests();
}); });
afterAll(() => { afterAll(() => {
global.server.close(); global.server.close();
console.log("Closing i18n MSW server!"); MockConsole.printPostTestWarnings();
console.log(chalk.hex("#dfb8d8")("Closing i18n MSW server!"));
}); });