Skip to content

Add and implement toHaveAbility matcher #1287

Description

@DayKev

Suggestion by flx (text from #1252 (comment)):

We should probably add a toHaveAbility() custom matcher

/* biome-ignore-start lint/correctness/noUnusedImports: tsdoc imports */
import type { Pokemon } from "#field/pokemon";
/* biome-ignore-end lint/correctness/noUnusedImports: tsdoc imports */

import { getPokemonNameWithAffix } from "#app/messages";
import { AbilityId } from "#enums/ability-id";
import { isPokemonInstance, receivedStr } from "#test/test-utils/test-utils";
import type { MatcherState, SyncExpectationResult } from "@vitest/expect";

/**
 * Matcher to check if a {@linkcode Pokemon} had a specific {@linkcode AbilityId}.
 * @param received - The object to check. Should be a {@linkcode Pokemon}.
 * @param expectedAbility - The {@linkcode AbilityId} to check for.
 * @returns Whether the matcher passed
 */
export function toHaveAbilityMatcher(
  this: MatcherState,
  received: unknown,
  expectedAbilityId: AbilityId,
): SyncExpectationResult {
  if (!isPokemonInstance(received)) {
    return {
      pass: this.isNot,
      message: () => `Expected Pokemon, but got ${receivedStr(received)}!`,
    };
  }

  const actualAbilityId = received.getAbility().id;
  const pass = expectedAbilityId === actualAbilityId;

  const pkmName = getPokemonNameWithAffix(received);
  const expectedAbilityStr = `${AbilityId[expectedAbilityId]} (=${expectedAbilityId})`;
  const actualAbilityStr = `${AbilityId[actualAbilityId]} (=${actualAbilityId})`;

  return {
    pass,
    message: () =>
      pass
        ? `Expected ${pkmName} to NOT have ${expectedAbilityStr} ability, but it did!`
        : `Expected ${pkmName} to have ${expectedAbilityStr} ability, but found ${actualAbilityStr} instead.`,
  };
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    TestsAutomated tests related

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions