[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,12 +27,33 @@ 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
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).
*
@ -38,40 +63,56 @@ declare module "vitest" {
* @param expected - The expected contents of the array, in any order
* @see {@linkcode expect.arrayContaining}
*/
toEqualArrayUnsorted(expected: T[]): void;
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 battle.
* @param expectedMessage - The expected message
* 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;
/**
* @param expectedPhase - The expected {@linkcode PhaseString}
* 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
} // #endregion GameManager Matchers
// #region Arena Matchers
interface ArenaMatchers {
/**
* Check whether the current {@linkcode WeatherType} is as expected.
* @param expectedWeatherType - The expected {@linkcode WeatherType}
* @param expectedWeatherType - The expected `WeatherType`
*/
toHaveWeather(expectedWeatherType: WeatherType): void;
/**
* Check whether the current {@linkcode TerrainType} is as expected.
* @param expectedTerrainType - The expected {@linkcode TerrainType}
* @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 {@linkcode ArenaTag} containing the desired properties
* @param expectedTag - A partially-filled `ArenaTag` containing the desired properties
*/
toHaveArenaTag<A extends ArenaTagType>(expectedTag: toHaveArenaTagOptions<A>): void;
/**
@ -89,15 +130,16 @@ declare module "vitest" {
/**
* 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;
* @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`
@ -181,6 +223,7 @@ declare module "vitest" {
* 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
@ -191,7 +234,5 @@ declare module "vitest" {
* 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
*/