StringAPI ReferenceTesting Utilities API

Testing Utilities API

Complete API reference for ANSI string testing utilities in @visulima/string.

Testing Utilities API

Detailed API reference for the ANSI string testing and comparison utilities.

toEqualAnsi

A Vitest custom matcher for comparing ANSI-encoded strings. Provides detailed error output when strings do not match, showing both the visible content and the underlying escape codes.

function toEqualAnsi(
    actual: string,
    expected: string
): ExpectationResult;

Import:

import { toEqualAnsi } from "@visulima/string/test/vitest";

Parameters:

ParameterTypeDescription
actualstringThe actual ANSI string received.
expectedstringThe expected ANSI string.

Returns: ExpectationResult -- An object with pass (boolean) and message (function returning a string).

Setup:

import { expect } from "vitest";
import { toEqualAnsi } from "@visulima/string/test/vitest";

expect.extend({ toEqualAnsi });

Usage in tests:

it("should match colored output", () => {
    const actual = "\x1b[31mError\x1b[39m";
    const expected = "\x1b[31mError\x1b[39m";

    expect(actual).toEqualAnsi(expected);
});

Error output: When the assertion fails, the message includes:

  • Visible content of both strings (with ANSI codes stripped)
  • Escape codes shown as visible characters
  • JSON-encoded representation
  • Visual width of each string
  • Whether the visible content is identical (indicating only escape codes differ)

ExpectationResult

interface ExpectationResult {
    /** Whether the assertion passed. */
    pass: boolean;

    /** Function returning the error message for display. */
    message: () => string;

    /** The actual value (optional, for diff display). */
    actual?: unknown;

    /** The expected value (optional, for diff display). */
    expected?: unknown;
}

CustomMatchers

TypeScript interface for extending Vitest's expect:

interface CustomMatchers {
    toEqualAnsi: (expected: string) => ExpectationResult;
}

formatAnsiString

Formats an ANSI string into multiple representations for debugging and test output.

function formatAnsiString(ansiString: string): {
    ansi: string;
    json: string;
    lengthDifference: number;
    stripped: string;
    visible: string;
};

Import:

import { formatAnsiString } from "@visulima/string/test/utils";

Parameters:

ParameterTypeDescription
ansiStringstringThe ANSI string to format.

Returns: An object with the following properties:

PropertyTypeDescription
ansistringThe original ANSI string, unchanged.
strippedstringThe string with all ANSI/VT control characters removed (using node:util.stripVTControlCharacters).
visiblestringThe string with escape characters replaced by the literal text \u001B so they are visible.
jsonstringThe JSON.stringify output, showing all escape codes as \u001b sequences.
lengthDifferencenumberThe difference in .length between the original and stripped string, indicating how many characters are ANSI codes.

Examples:

const colored = "\x1b[31mError\x1b[39m";
const formatted = formatAnsiString(colored);

formatted.ansi;              // '\x1b[31mError\x1b[39m'
formatted.stripped;          // 'Error'
formatted.visible;           // '\\u001B[31mError\\u001B[39m'
formatted.json;              // '"\\u001b[31mError\\u001b[39m"'
formatted.lengthDifference;  // 9

expectAnsiStrings

Creates a detailed comparison result for two ANSI strings. This is the underlying implementation used by toEqualAnsi.

function expectAnsiStrings(
    actual: string,
    expected: string
): ExpectationResult;

Import:

import { expectAnsiStrings } from "@visulima/string/test/utils";

Parameters:

ParameterTypeDescription
actualstringThe actual ANSI string.
expectedstringThe expected ANSI string.

Returns: ExpectationResult -- The same result type as toEqualAnsi.

Examples:

const result = expectAnsiStrings(
    "\x1b[31mError\x1b[39m",
    "\x1b[32mError\x1b[39m"
);

result.pass;       // false (different color codes)
result.message();  // Detailed diff message

compareAnsiStrings

Performs a detailed comparison between two ANSI strings, returning structured data about the differences.

function compareAnsiStrings(
    actual: string,
    expected: string
): {
    actual: ReturnType<typeof formatAnsiString>;
    ansiEqual: boolean;
    expected: ReturnType<typeof formatAnsiString>;
    strippedEqual: boolean;
    summary: {
        actualLength: number;
        actualStrippedLength: number;
        ansiEqual: boolean;
        expectedLength: number;
        expectedStrippedLength: number;
        strippedEqual: boolean;
    };
};

Import:

import { compareAnsiStrings } from "@visulima/string/test/utils";

Parameters:

ParameterTypeDescription
actualstringThe actual ANSI string.
expectedstringThe expected ANSI string.

Returns: An object with:

PropertyTypeDescription
actualobjectThe formatAnsiString result for the actual string.
expectedobjectThe formatAnsiString result for the expected string.
ansiEqualbooleanWhether the full strings (including ANSI codes) are identical.
strippedEqualbooleanWhether the visible content (ANSI codes stripped) is identical.
summaryobjectAggregate comparison data including lengths and equality flags.

Examples:

const result = compareAnsiStrings(
    "\x1b[31mError\x1b[39m",
    "\x1b[32mError\x1b[39m"
);

result.ansiEqual;     // false
result.strippedEqual; // true (both say "Error")
result.summary.actualLength;          // 14
result.summary.actualStrippedLength;  // 5
result.summary.expectedLength;        // 14
result.summary.expectedStrippedLength; // 5

Use case: Useful when you need programmatic access to the comparison data rather than just a pass/fail assertion:

it("should use correct colors", () => {
    const output = generateOutput();
    const expected = generateExpected();

    const comparison = compareAnsiStrings(output, expected);

    if (!comparison.ansiEqual && comparison.strippedEqual) {
        console.log("Content matches but ANSI codes differ");
        console.log("Actual JSON:", comparison.actual.json);
        console.log("Expected JSON:", comparison.expected.json);
    }

    expect(comparison.ansiEqual).toBe(true);
});

Notes

  • All ANSI stripping uses Node.js built-in stripVTControlCharacters from node:util.
  • The toEqualAnsi matcher uses getStringWidth from @visulima/string to calculate the visual width shown in error messages.
  • These utilities work with any ANSI escape codes, including SGR (colors, bold, underline), OSC (hyperlinks), and other VT control sequences.
  • The test/vitest export provides the matcher function directly; the test/utils export provides the lower-level utilities for custom testing setups.
Support

Contribute to our work and keep us going

Community is the heart of open source. The success of our packages wouldn't be possible without the incredible contributions of users, testers, and developers who collaborate with us every day.Want to get involved? Here are some tips on how you can make a meaningful impact on our open source projects.

Ready to help us out?

Be sure to check out the package's contribution guidelines first. They'll walk you through the process on how to properly submit an issue or pull request to our repositories.

Submit a pull request

Found something to improve? Fork the repo, make your changes, and open a PR. We review every contribution and provide feedback to help you get merged.

Good first issues

Simple issues suited for people new to open source development, and often a good place to start working on a package.
View good first issues