testing.ts

Shared test assertions for the @fuzdev ecosystem.

Extends the fuz-stack testing conventions (assert from vitest, tests in src/test/, plain object mocks) with reusable helpers for patterns that appear across multiple repos. Only depends on vitest — safe for fuz_util's zero-runtime-deps constraint.

view source

Declarations
#

4 declarations

assert_property
#

testing.ts view source

<R extends object, P extends keyof R, const V extends R[P]>(obj: R, property: P, value: V): asserts obj is Extract<R, Record<P, V>> import {assert_property} from '@fuzdev/fuz_util/testing.js';

Narrows a discriminated union by a literal property value, failing the test if the value doesn't match. The assertion signature propagates the narrowed type so callers can access variant-specific fields directly.

Works with any discriminator key (kind, ok, type, _tag, etc.).

obj

type R

property

type P

value

type V

returns

void

generics

assert_property<R extends object, P extends keyof R, V extends R[P]>
R
constraint object
P
constraint keyof R
V
constraint R[P]

examples

type Shape = | {kind: 'circle'; radius: number} | {kind: 'square'; side: number}; const shape: Shape = get_shape(); assert_property(shape, 'kind', 'circle'); assert.strictEqual(shape.radius, 5); // `radius` now typed as `number`

assert_rejects
#

testing.ts view source

(fn: () => Promise<unknown>, pattern?: RegExp | undefined): Promise<Error> import {assert_rejects} from '@fuzdev/fuz_util/testing.js';

Asserts that fn rejects with an Error. Optionally matches the error message against pattern. Returns the caught Error for further assertions by the caller.

assert.fail is placed after the catch block so that assertion failures from the test itself are not swallowed by the catch.

fn

async function expected to reject

type () => Promise<unknown>

pattern?

optional regex to match against the error message

type RegExp | undefined
optional

returns

Promise<Error>

the caught Error

create_mock_logger
#

testing.ts view source

(): MockLogger import {create_mock_logger} from '@fuzdev/fuz_util/testing.js';

Creates a mock Logger with vi.fn() on each logging method and tracking arrays for inspecting logged messages. Follows the fuz-stack convention of plain object mocks over mocking libraries.

returns

MockLogger

MockLogger
#

testing.ts view source

MockLogger import type {MockLogger} from '@fuzdev/fuz_util/testing.js';

A mock Logger with vi.fn() methods and call tracking arrays. Assignable to Logger for use in code under test. Each tracking array captures the first argument of each call. For full call details, use vi.fn() introspection on the methods directly.

label?

type string

readonly

parent?

type Logger

readonly

#level_override?

type LogLevel

#colors_override?

type boolean

#console_override?

type LogConsole

#cached_colors?

type boolean

#cached_st?

type (format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string

#cached_error?

type string

#cached_warn?

type string

#cached_info?

type string

#cached_debug?

type string

#cached_level_string?

type LogLevel

#cached_level?

type number

level

Dynamic getter for level - checks override, then parent, then default.

type LogLevel

colors

Dynamic getter for colors - checks override, then parent, then environment variables.

Colors are disabled if either the NO_COLOR or CLAUDECODE environment variable is set. The CLAUDECODE check disables colors in Claude Code environments where ANSI color codes may not render correctly in the output.

type boolean

console

Dynamic getter for console - checks override, then parent, then global console.

type LogConsole

root

Gets the root logger by walking up the parent chain. Useful for setting global configuration that affects all child loggers.

type Logger

clear_level_override

Clears the level override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit the level from its parent (or use the default level if it has no parent).

type (): void

returns void

clear_colors_override

Clears the colors override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit colors from its parent (or use the default colors behavior if it has no parent).

type (): void

returns void

clear_console_override

Clears the console override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit the console from its parent (or use the global console if it has no parent).

type (): void

returns void

#ensure_cache_valid

Ensures prefix cache is valid by checking if colors configuration changed. Uses pull-based invalidation: checks colors on each access and invalidates cached prefixes if colors changed. This automatically handles inheritance changes since this.colors getter walks the parent chain on each access.

Invalidates all 4 cached prefix strings when colors change, since they all depend on the color configuration.

type (): void

returns void

#format_label

Formats the label portion of log output with given styleText function. Applies color styling if enabled, otherwise returns plain bracketed label.

type (st: (format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string, colored: boolean): string

st

type (format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string

colored

type boolean
returns string

#get_error_prefix

Gets the formatted error prefix, lazily computing and caching if needed. Lazy computation means prefixes are only built when the corresponding log method is first called, avoiding work for unused log levels.

type (): string

returns string

#get_warn_prefix

Gets the formatted warn prefix, lazily computing and caching if needed.

type (): string

returns string

#get_info_prefix

Gets the formatted info prefix, lazily computing and caching if needed. Note: info has no colored prefix character, only the label.

type (): string

returns string

#get_debug_prefix

Gets the formatted debug prefix, lazily computing and caching if needed.

type (): string

returns string

#get_cached_level

Gets the cached numeric level value, updating cache if level changed. Called on every log method invocation to check if the message should be filtered. Caches the numeric value (from LOG_LEVEL_VALUES dictionary) to avoid repeated lookups. Uses pull-based invalidation: checks this.level getter which handles inheritance.

type (): number

returns number

child

Creates a child logger with automatic label concatenation. Children inherit parent configuration unless overridden.

type (label: string, options?: LoggerOptions): Logger

label

child label (will be concatenated with parent label using :) Cannot be an empty string - empty labels would result in confusing output like parent: with a trailing colon. Use undefined or '' only for root loggers.

type string

options

optional configuration overrides

default {}
returns Logger

new Logger instance with concatenated label

const app_log = new Logger('app'); const db_log = app_log.child('db'); // label: 'app:db' const query_log = db_log.child('query'); // label: 'app:db:query'

throws

  • Error - if label is an empty string

error

Logs an error message with 🞩error🞩 prefix. Only outputs if current level is error or higher.

type (...args: unknown[]): void

args

type unknown[]
returns void

warn

Logs a warning message with ⚑warn⚑ prefix. Only outputs if current level is warn or higher.

type (...args: unknown[]): void

args

type unknown[]
returns void

info

Logs an informational message. Unlike error/warn/debug, info has no character prefix - only the label is shown. This keeps standard output clean since info is the default log level. Only outputs if current level is info or higher.

type (...args: unknown[]): void

args

type unknown[]
returns void

debug

Logs a debug message with ┆debug┆ prefix. Only outputs if current level is debug.

type (...args: unknown[]): void

args

type unknown[]
returns void

raw

Logs raw output without any prefix, formatting, or level filtering. Bypasses the logger's level checking, prefix formatting, and color application entirely.

Note: This method ignores the configured log level - it always outputs regardless of whether the logger is set to 'off' or any other level.

type (...args: unknown[]): void

args

type unknown[]
returns void

error_calls

type unknown[]

warn_calls

type unknown[]

info_calls

type unknown[]

debug_calls

type unknown[]

Depends on
#