[Test] Added Map key matcher; enforced strong typing on matchers (#6561)

* Added `toHaveKey` matcher + fixed imports

* Broke up the test matchers into multiple smaller interfaces

* Added restricted typing on matchers

Now we can't call `expect(game).toHaveFullHp()`!!!!!

* Updated comment

* Renamed `toEqualArrayUnsorted` into `toEqualUnsorted`

* Moved comment at top of file

* Fix `@module` doc comment

* Remove extra space

* Fix typo

* Fixed key ssue in matchers

* Update to-have-key.ts

* Update test/@types/vitest.d.ts

Co-authored-by: NightKev <34855794+DayKev@users.noreply.github.com>

* Fixed missing braces inside comment

---------

Co-authored-by: NightKev <34855794+DayKev@users.noreply.github.com>
This commit is contained in:
Bertie690 2025-09-20 18:24:27 -04:00 committed by GitHub
parent 207808f37d
commit 1691951c87
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 274 additions and 190 deletions

View File

@ -1,7 +1,7 @@
import "vitest";
import type { Phase } from "#app/phase";
import type Overrides from "#app/overrides";
import type { Phase } from "#app/phase";
import type { ArenaTag } from "#data/arena-tag";
import type { TerrainType } from "#data/terrain";
import type { AbilityId } from "#enums/ability-id";
@ -10,10 +10,14 @@ import type { ArenaTagType } from "#enums/arena-tag-type";
import type { BattlerTagType } from "#enums/battler-tag-type";
import type { MoveId } from "#enums/move-id";
import type { PokemonType } from "#enums/pokemon-type";
import type { PositionalTag } from "#data/positional-tags/positional-tag";
import type { PositionalTagType } from "#enums/positional-tag-type";
import type { BattleStat, EffectiveStat } from "#enums/stat";
import type { WeatherType } from "#enums/weather-type";
import type { Pokemon } from "#field/pokemon";
import type { GameManager } from "#test/test-utils/game-manager";
import type { toHaveArenaTagOptions } from "#test/test-utils/matchers/to-have-arena-tag";
import type { toHaveBattlerTagOptions } from "#test/test-utils/matchers/to-have-battler-tag";
import type { toHaveEffectiveStatOptions } from "#test/test-utils/matchers/to-have-effective-stat";
import type { toHavePositionalTagOptions } from "#test/test-utils/matchers/to-have-positional-tag";
import type { expectedStatusType } from "#test/test-utils/matchers/to-have-status-effect";
@ -23,175 +27,212 @@ import type { TurnMove } from "#types/turn-move";
import type { AtLeastOne } from "#types/type-helpers";
import type { toDmgValue } from "#utils/common";
import type { expect } from "vitest";
import type { toHaveBattlerTagOptions } from "#test/test-utils/matchers/to-have-battler-tag";
// #region Boilerplate/Helpers
declare module "vitest" {
interface Assertion<T> {
// #region Generic Matchers
/**
* Check whether an array contains EXACTLY the given items (in any order).
*
* Different from {@linkcode expect.arrayContaining} as the latter only checks for subset equality
* (as opposed to full equality).
*
* @param expected - The expected contents of the array, in any order
* @see {@linkcode expect.arrayContaining}
*/
toEqualArrayUnsorted(expected: T[]): void;
// #endregion Generic Matchers
// #region GameManager Matchers
/**
* Check if the {@linkcode GameManager} has shown the given message at least once in the current battle.
* @param expectedMessage - The expected message
*/
toHaveShownMessage(expectedMessage: string): void;
/**
* @param expectedPhase - The expected {@linkcode PhaseString}
*/
toBeAtPhase(expectedPhase: PhaseString): void;
// #endregion GameManager Matchers
// #region Arena Matchers
/**
* Check whether the current {@linkcode WeatherType} is as expected.
* @param expectedWeatherType - The expected {@linkcode WeatherType}
*/
toHaveWeather(expectedWeatherType: WeatherType): void;
/**
* Check whether the current {@linkcode TerrainType} is as expected.
* @param expectedTerrainType - The expected {@linkcode TerrainType}
*/
toHaveTerrain(expectedTerrainType: TerrainType): void;
/**
* Check whether the current {@linkcode Arena} contains the given {@linkcode ArenaTag}.
* @param expectedTag - A partially-filled {@linkcode ArenaTag} containing the desired properties
*/
toHaveArenaTag<A extends ArenaTagType>(expectedTag: toHaveArenaTagOptions<A>): void;
/**
* Check whether the current {@linkcode Arena} contains the given {@linkcode ArenaTag}.
* @param expectedType - The {@linkcode ArenaTagType} of the desired tag
* @param side - The {@linkcode ArenaTagSide | side(s) of the field} the tag should affect; default {@linkcode ArenaTagSide.BOTH}
*/
toHaveArenaTag(expectedType: ArenaTagType, side?: ArenaTagSide): void;
/**
* Check whether the current {@linkcode Arena} contains the given {@linkcode PositionalTag}.
* @param expectedTag - A partially-filled `PositionalTag` containing the desired properties
*/
toHavePositionalTag<P extends PositionalTagType>(expectedTag: toHavePositionalTagOptions<P>): void;
/**
* Check whether the current {@linkcode Arena} contains the given number of {@linkcode PositionalTag}s.
* @param expectedType - The {@linkcode PositionalTagType} of the desired tag
* @param count - The number of instances of {@linkcode expectedType} that should be active;
* defaults to `1` and must be within the range `[0, 4]`
*/
toHavePositionalTag(expectedType: PositionalTagType, count?: number): void;
// #endregion Arena Matchers
// #region Pokemon Matchers
/**
* Check whether a {@linkcode Pokemon}'s current typing includes the given types.
* @param expectedTypes - The expected {@linkcode PokemonType}s to check against; must have length `>0`
* @param options - The {@linkcode toHaveTypesOptions | options} passed to the matcher
*/
toHaveTypes(expectedTypes: PokemonType[], options?: toHaveTypesOptions): void;
/**
* Check whether a {@linkcode Pokemon} has used a move matching the given criteria.
* @param expectedMove - The {@linkcode MoveId} the Pokemon is expected to have used,
* or a partially filled {@linkcode TurnMove} containing the desired properties to check
* @param index - The index of the move history entry to check, in order from most recent to least recent; default `0`
* @see {@linkcode Pokemon.getLastXMoves}
*/
toHaveUsedMove(expectedMove: MoveId | AtLeastOne<TurnMove>, index?: number): void;
/**
* Check whether a {@linkcode Pokemon}'s effective stat is as expected
* (checked after all stat value modifications).
* @param stat - The {@linkcode EffectiveStat} to check
* @param expectedValue - The expected value of {@linkcode stat}
* @param options - The {@linkcode toHaveEffectiveStatOptions | options} passed to the matcher
* @remarks
* If you want to check the stat **before** modifiers are applied, use {@linkcode Pokemon.getStat} instead.
*/
toHaveEffectiveStat(stat: EffectiveStat, expectedValue: number, options?: toHaveEffectiveStatOptions): void;
/**
* Check whether a {@linkcode Pokemon} has a specific {@linkcode StatusEffect | non-volatile status effect}.
* @param expectedStatusEffect - The {@linkcode StatusEffect} the Pokemon is expected to have,
* or a partially filled {@linkcode Status} containing the desired properties
*/
toHaveStatusEffect(expectedStatusEffect: expectedStatusType): void;
/**
* Check whether a {@linkcode Pokemon} has a specific {@linkcode Stat} stage.
* @param stat - The {@linkcode BattleStat} to check
* @param expectedStage - The expected stat stage value of {@linkcode stat}
*/
toHaveStatStage(stat: BattleStat, expectedStage: number): void;
/**
* Check whether a {@linkcode Pokemon} has the given {@linkcode BattlerTag}.
* @param expectedTag - A partially-filled {@linkcode BattlerTag} containing the desired properties
*/
toHaveBattlerTag<B extends BattlerTagType>(expectedTag: toHaveBattlerTagOptions<B>): void;
/**
* Check whether a {@linkcode Pokemon} has the given {@linkcode BattlerTag}.
* @param expectedType - The expected {@linkcode BattlerTagType}
*/
toHaveBattlerTag(expectedType: BattlerTagType): void;
/**
* Check whether a {@linkcode Pokemon} has applied a specific {@linkcode AbilityId}.
* @param expectedAbilityId - The `AbilityId` to check for
*/
toHaveAbilityApplied(expectedAbilityId: AbilityId): void;
/**
* Check whether a {@linkcode Pokemon} has a specific amount of {@linkcode Stat.HP | HP}.
* @param expectedHp - The expected amount of {@linkcode Stat.HP | HP} to have
*/
toHaveHp(expectedHp: number): void;
/**
* Check whether a {@linkcode Pokemon} has taken a specific amount of damage.
* @param expectedDamageTaken - The expected amount of damage taken
* @param roundDown - Whether to round down `expectedDamageTaken` with {@linkcode toDmgValue}; default `true`
*/
toHaveTakenDamage(expectedDamageTaken: number, roundDown?: boolean): void;
/**
* Check whether a {@linkcode Pokemon} is currently fainted (as determined by {@linkcode Pokemon.isFainted}).
* @remarks
* When checking whether an enemy wild Pokemon is fainted, one must store a reference to it in a variable _before_ the fainting effect occurs.
* Otherwise, the Pokemon will be removed from the field and garbage collected.
*/
toHaveFainted(): void;
/**
* Check whether a {@linkcode Pokemon} is at full HP.
*/
toHaveFullHp(): void;
/**
* Check whether a {@linkcode Pokemon} has consumed the given amount of PP for one of its moves.
* @param moveId - The {@linkcode MoveId} corresponding to the {@linkcode PokemonMove} that should have consumed PP
* @param ppUsed - The numerical amount of PP that should have been consumed,
* or `all` to indicate the move should be _out_ of PP
* @remarks
* If the Pokemon's moveset has been set via {@linkcode Overrides.MOVESET_OVERRIDE}/{@linkcode Overrides.ENEMY_MOVESET_OVERRIDE}
* or does not contain exactly one copy of `moveId`, this will fail the test.
*/
toHaveUsedPP(moveId: MoveId, ppUsed: number | "all"): void;
// #endregion Pokemon Matchers
}
interface Assertion<T>
extends GenericMatchers<T>,
RestrictMatcher<GameManagerMatchers, T, GameManager>,
RestrictMatcher<ArenaMatchers, T, GameManager>,
RestrictMatcher<PokemonMatchers, T, Pokemon> {}
}
/**
* Utility type to restrict matchers' properties based on the type of `T`.
* If it does not extend `R`, all methods inside `M` will have their types resolved to `never`.
* @typeParam M - The type of the matchers object to restrict
* @typeParam T - The type parameter of the assertion
* @typeParam R - The type to restrict T based off of
* @privateRemarks
* We cannot remove incompatible methods outright as Typescript requires that
* interfaces extend solely off of types with statically known members.
*/
type RestrictMatcher<M extends object, T, R> = {
[k in keyof M]: T extends R ? M[k] : never;
};
// #endregion Boilerplate/Helpers
// #region Generic Matchers
interface GenericMatchers<T> {
/**
* Check whether an array contains EXACTLY the given items (in any order).
*
* Different from {@linkcode expect.arrayContaining} as the latter only checks for subset equality
* (as opposed to full equality).
*
* @param expected - The expected contents of the array, in any order
* @see {@linkcode expect.arrayContaining}
*/
toEqualUnsorted: T extends (infer U)[] ? (expected: U[]) => void : never;
/**
* Check whether a {@linkcode Map} contains the given key, disregarding its value.
* @param expectedKey - The key whose inclusion is being checked
* @privateRemarks
* While this functionality _could_ be simulated by writing
* `expect(x.get(y)).toBeDefined()` or
* `expect(x).toContain([y, expect.anything()])`,
* this is still preferred due to being more ergonomic and provides better error messsages.
*/
toHaveKey: T extends Map<infer K, unknown> ? (expectedKey: K) => void : never;
}
// #endregion Generic Matchers
// #region GameManager Matchers
interface GameManagerMatchers {
/**
* Check if the {@linkcode GameManager} has shown the given message at least once in the current test case.
* @param expectedMessage - The expected message to be displayed
* @remarks
* Strings consumed by this function should _always_ be produced by a call to `i18next.t`
* to avoid hardcoding text into test files.
*/
toHaveShownMessage(expectedMessage: string): void;
/**
* Check if the currently-running {@linkcode Phase} is of the given type.
* @param expectedPhase - The expected {@linkcode PhaseString | name of the phase}
*/
toBeAtPhase(expectedPhase: PhaseString): void;
} // #endregion GameManager Matchers
// #region Arena Matchers
interface ArenaMatchers {
/**
* Check whether the current {@linkcode WeatherType} is as expected.
* @param expectedWeatherType - The expected `WeatherType`
*/
toHaveWeather(expectedWeatherType: WeatherType): void;
/**
* Check whether the current {@linkcode TerrainType} is as expected.
* @param expectedTerrainType - The expected `TerrainType`
*/
toHaveTerrain(expectedTerrainType: TerrainType): void;
/**
* Check whether the current {@linkcode Arena} contains the given {@linkcode ArenaTag}.
* @param expectedTag - A partially-filled `ArenaTag` containing the desired properties
*/
toHaveArenaTag<A extends ArenaTagType>(expectedTag: toHaveArenaTagOptions<A>): void;
/**
* Check whether the current {@linkcode Arena} contains the given {@linkcode ArenaTag}.
* @param expectedType - The {@linkcode ArenaTagType} of the desired tag
* @param side - The {@linkcode ArenaTagSide | side(s) of the field} the tag should affect; default {@linkcode ArenaTagSide.BOTH}
*/
toHaveArenaTag(expectedType: ArenaTagType, side?: ArenaTagSide): void;
/**
* Check whether the current {@linkcode Arena} contains the given {@linkcode PositionalTag}.
* @param expectedTag - A partially-filled `PositionalTag` containing the desired properties
*/
toHavePositionalTag<P extends PositionalTagType>(expectedTag: toHavePositionalTagOptions<P>): void;
/**
* Check whether the current {@linkcode Arena} contains the given number of {@linkcode PositionalTag}s.
* @param expectedType - The {@linkcode PositionalTagType} of the desired tag
* @param count - The number of instances of `expectedType` that should be active;
* defaults to `1` and must be within the range `[0, 4]`
*/
toHavePositionalTag(expectedType: PositionalTagType, count?: number): void;
}
// #endregion Arena Matchers
// #region Pokemon Matchers
interface PokemonMatchers {
/**
* Check whether a {@linkcode Pokemon}'s current typing includes the given types.
* @param expectedTypes - The expected {@linkcode PokemonType}s to check against; must have length `>0`
* @param options - The {@linkcode toHaveTypesOptions | options} passed to the matcher
*/
toHaveTypes(expectedTypes: PokemonType[], options?: toHaveTypesOptions): void;
/**
* Check whether a {@linkcode Pokemon} has used a move matching the given criteria.
* @param expectedMove - The {@linkcode MoveId} the Pokemon is expected to have used,
* or a partially filled {@linkcode TurnMove} containing the desired properties to check
* @param index - The index of the move history entry to check, in order from most recent to least recent; default `0`
* @see {@linkcode Pokemon.getLastXMoves}
*/
toHaveUsedMove(expectedMove: MoveId | AtLeastOne<TurnMove>, index?: number): void;
/**
* Check whether a {@linkcode Pokemon}'s effective stat is as expected
* (checked after all stat value modifications).
* @param stat - The {@linkcode EffectiveStat} to check
* @param expectedValue - The expected value of {@linkcode stat}
* @param options - The {@linkcode toHaveEffectiveStatOptions | options} passed to the matcher
* @remarks
* If you want to check the stat **before** modifiers are applied, use {@linkcode Pokemon.getStat} instead.
*/
toHaveEffectiveStat(stat: EffectiveStat, expectedValue: number, options?: toHaveEffectiveStatOptions): void;
/**
* Check whether a {@linkcode Pokemon} has a specific {@linkcode StatusEffect | non-volatile status effect}.
* @param expectedStatusEffect - The {@linkcode StatusEffect} the Pokemon is expected to have,
* or a partially filled {@linkcode Status} containing the desired properties
*/
toHaveStatusEffect(expectedStatusEffect: expectedStatusType): void;
/**
* Check whether a {@linkcode Pokemon} has a specific {@linkcode Stat} stage.
* @param stat - The {@linkcode BattleStat} to check
* @param expectedStage - The expected stat stage value of {@linkcode stat}
*/
toHaveStatStage(stat: BattleStat, expectedStage: number): void;
/**
* Check whether a {@linkcode Pokemon} has the given {@linkcode BattlerTag}.
* @param expectedTag - A partially-filled {@linkcode BattlerTag} containing the desired properties
*/
toHaveBattlerTag<B extends BattlerTagType>(expectedTag: toHaveBattlerTagOptions<B>): void;
/**
* Check whether a {@linkcode Pokemon} has the given {@linkcode BattlerTag}.
* @param expectedType - The expected {@linkcode BattlerTagType}
*/
toHaveBattlerTag(expectedType: BattlerTagType): void;
/**
* Check whether a {@linkcode Pokemon} has applied a specific {@linkcode AbilityId}.
* @param expectedAbilityId - The `AbilityId` to check for
*/
toHaveAbilityApplied(expectedAbilityId: AbilityId): void;
/**
* Check whether a {@linkcode Pokemon} has a specific amount of {@linkcode Stat.HP | HP}.
* @param expectedHp - The expected amount of {@linkcode Stat.HP | HP} to have
*/
toHaveHp(expectedHp: number): void;
/**
* Check whether a {@linkcode Pokemon} has taken a specific amount of damage.
* @param expectedDamageTaken - The expected amount of damage taken
* @param roundDown - Whether to round down `expectedDamageTaken` with {@linkcode toDmgValue}; default `true`
*/
toHaveTakenDamage(expectedDamageTaken: number, roundDown?: boolean): void;
/**
* Check whether a {@linkcode Pokemon} is currently fainted (as determined by {@linkcode Pokemon.isFainted}).
* @remarks
* When checking whether an enemy wild Pokemon is fainted, one must store a reference to it in a variable _before_ the fainting effect occurs.
* Otherwise, the Pokemon will be removed from the field and garbage collected.
*/
toHaveFainted(): void;
/**
* Check whether a {@linkcode Pokemon} is at full HP.
*/
toHaveFullHp(): void;
/**
* Check whether a {@linkcode Pokemon} has consumed the given amount of PP for one of its moves.
* @param moveId - The {@linkcode MoveId} corresponding to the {@linkcode PokemonMove} that should have consumed PP
* @param ppUsed - The numerical amount of PP that should have been consumed,
* or `all` to indicate the move should be _out_ of PP
* @remarks
* If the Pokemon's moveset has been set via {@linkcode Overrides.MOVESET_OVERRIDE}/{@linkcode Overrides.ENEMY_MOVESET_OVERRIDE}
* or does not contain exactly one copy of `moveId`, this will fail the test.
*/
toHaveUsedPP(moveId: MoveId, ppUsed: number | "all"): void;
}
// #endregion Pokemon Matchers

View File

@ -1,5 +1,11 @@
/**
* Setup file for custom matchers.
* Make sure to define the call signatures in `#test/@types/vitest.d.ts` too!
* @module
*/
import { toBeAtPhase } from "#test/test-utils/matchers/to-be-at-phase";
import { toEqualArrayUnsorted } from "#test/test-utils/matchers/to-equal-array-unsorted";
import { toEqualUnsorted } from "#test/test-utils/matchers/to-equal-unsorted";
import { toHaveAbilityApplied } from "#test/test-utils/matchers/to-have-ability-applied";
import { toHaveArenaTag } from "#test/test-utils/matchers/to-have-arena-tag";
import { toHaveBattlerTag } from "#test/test-utils/matchers/to-have-battler-tag";
@ -7,6 +13,7 @@ import { toHaveEffectiveStat } from "#test/test-utils/matchers/to-have-effective
import { toHaveFainted } from "#test/test-utils/matchers/to-have-fainted";
import { toHaveFullHp } from "#test/test-utils/matchers/to-have-full-hp";
import { toHaveHp } from "#test/test-utils/matchers/to-have-hp";
import { toHaveKey } from "#test/test-utils/matchers/to-have-key";
import { toHavePositionalTag } from "#test/test-utils/matchers/to-have-positional-tag";
import { toHaveShownMessage } from "#test/test-utils/matchers/to-have-shown-message";
import { toHaveStatStage } from "#test/test-utils/matchers/to-have-stat-stage";
@ -19,13 +26,9 @@ import { toHaveUsedPP } from "#test/test-utils/matchers/to-have-used-pp";
import { toHaveWeather } from "#test/test-utils/matchers/to-have-weather";
import { expect } from "vitest";
/*
* Setup file for custom matchers.
* Make sure to define the call signatures in `#test/@types/vitest.d.ts` too!
*/
expect.extend({
toEqualArrayUnsorted,
toEqualUnsorted,
toHaveKey,
toHaveShownMessage,
toBeAtPhase,
toHaveWeather,

View File

@ -40,10 +40,7 @@ export class ModifierHelper extends GameManagerHelper {
* @returns `this`
*/
testCheck(modifier: ModifierTypeKeys, expectToBePreset: boolean): this {
if (expectToBePreset) {
expect(itemPoolChecks.get(modifier)).toBeTruthy();
}
expect(itemPoolChecks.get(modifier)).toBeFalsy();
(expectToBePreset ? expect(itemPoolChecks) : expect(itemPoolChecks).not).toHaveKey(modifier);
return this;
}

View File

@ -8,11 +8,7 @@ import type { MatcherState, SyncExpectationResult } from "@vitest/expect";
* @param expected - The array to check equality with
* @returns Whether the matcher passed
*/
export function toEqualArrayUnsorted(
this: MatcherState,
received: unknown,
expected: unknown[],
): SyncExpectationResult {
export function toEqualUnsorted(this: MatcherState, received: unknown, expected: unknown[]): SyncExpectationResult {
if (!Array.isArray(received)) {
return {
pass: this.isNot,

View File

@ -0,0 +1,47 @@
import { getOnelineDiffStr } from "#test/test-utils/string-utils";
import { receivedStr } from "#test/test-utils/test-utils";
import type { MatcherState, SyncExpectationResult } from "@vitest/expect";
/**
* Matcher that checks if a {@linkcode Map} contains the given key, regardless of its value.
* @param received - The received value. Should be a Map
* @param expectedKey - The key whose inclusion in the map is being checked
* @returns Whether the matcher passed
*/
export function toHaveKey(this: MatcherState, received: unknown, expectedKey: unknown): SyncExpectationResult {
if (!(received instanceof Map)) {
return {
pass: this.isNot,
message: () => `Expected to receive a Map, but got ${receivedStr(received)}!`,
};
}
if (received.size === 0) {
return {
pass: this.isNot,
message: () => "Expected to receive a non-empty Map, but received map was empty!",
expected: expectedKey,
actual: received,
};
}
const keys = [...received.keys()];
const pass = this.equals(keys, expectedKey, [
...this.customTesters,
this.utils.iterableEquality,
this.utils.subsetEquality,
]);
const actualStr = getOnelineDiffStr.call(this, received);
const expectedStr = getOnelineDiffStr.call(this, expectedKey);
return {
pass,
message: () =>
pass
? `Expected ${actualStr} to NOT have the key ${expectedStr}, but it did!`
: `Expected ${actualStr} to have the key ${expectedStr}, but it didn't!`,
expected: expectedKey,
actual: keys,
};
}

View File

@ -8,8 +8,8 @@ import { isGameManagerInstance, receivedStr } from "#test/test-utils/test-utils"
import type { MatcherState, SyncExpectationResult } from "@vitest/expect";
/**
* Matcher that checks if the {@linkcode TerrainType} is as expected
* @param received - The object to check. Should be an instance of {@linkcode GameManager}.
* Matcher that checks if the current {@linkcode TerrainType} is as expected.
* @param received - The object to check. Should be the current {@linkcode GameManager}.
* @param expectedTerrainType - The expected {@linkcode TerrainType}, or {@linkcode TerrainType.NONE} if no terrain should be active
* @returns Whether the matcher passed
*/

View File

@ -8,8 +8,8 @@ import { toTitleCase } from "#utils/strings";
import type { MatcherState, SyncExpectationResult } from "@vitest/expect";
/**
* Matcher that checks if the {@linkcode WeatherType} is as expected
* @param received - The object to check. Expects an instance of {@linkcode GameManager}.
* Matcher that checks if the current {@linkcode WeatherType} is as expected.
* @param received - The object to check. Should be the current {@linkcode GameManager}
* @param expectedWeatherType - The expected {@linkcode WeatherType}
* @returns Whether the matcher passed
*/