---
url: https://huldoser.github.io/test-inventory/guide/library.md
description: >-
  Scan, filter and compare inventories using the library, with TypeScript types
  and JSON Schemas.
---

# Library

The package also exports the functions the command line uses. It is ESM only.

For a complete runnable file, use the [library workflow](/guide/workflows#complete-library-script).
Feature-specific minimum versions are listed in [compatibility](/guide/compatibility).

```ts
import { filterInventory, pickTestFields, scan, scanSource } from 'test-inventory';
```

## scan

Scans the files that match the patterns and returns the inventory. The options are the same as on the
[command line](/guide/cli), in camel case, and `signal`, an `AbortSignal` that stops the scan between files, as a
server does when its client goes away.

```ts
/**
 * Scans the test files that match `patterns` under `root`, or without patterns those the configs run, one file at a
 * time.
 *
 * Throws a `TypeError` for invalid options. Problems with files and code are reported as diagnostics.
 */
export function scan(options: ScanOptions): Promise<Inventory>;

export interface ScanOptions {
  /**
   * Glob patterns for the test files, relative to `root`. As in the runners, they match names that start with a dot
   * too. Without them, the test files are those the configs in the root and the folders below it run, or for node:test
   * and Bun those `node --test` and `bun test` run.
   */
  patterns?: string[];
  /**
   * The runner whose tests are listed. Without it, the one the project uses: whose package a package.json in the root
   * or below lists, whose config is there, or for node:test and Bun, run by a package.json script, else one a
   * package.json above the root lists. With none of them or
   * several, the scan throws a `TypeError` that names them.
   */
  framework?: Framework;
  /** The project root. Paths in the output are relative to it. Defaults to the current directory. */
  root?: string;
  /** Glob patterns to leave out, in addition to `node_modules` and `.git`. */
  ignore?: string[];
  /** The framework version whose rules apply, instead of the one read from the project. */
  frameworkVersion?: string;
  /** Which tests get the comments above them. Defaults to `non-active`. */
  comments?: CommentsMode;
  /**
   * One test or describe per case of a `.each` or `.for` table and per pass of a loop whose values the scan can work
   * out, each with the title the runner gives it. Defaults to `false`: one record per declaration.
   */
  expandCases?: boolean;
  /**
   * Stops the scan when it aborts: the scan checks it before it starts and between files, and then rejects with the
   * signal's `reason`, as `fetch` does.
   */
  signal?: AbortSignal;
}

export type Framework =
  'playwright' | 'vitest' | 'jest' | 'mocha' | 'jasmine' | 'cypress' | 'webdriverio' | 'node' | 'bun';

export type CommentsMode = 'all' | 'non-active' | 'none';
```

To count the tests that are always skipped in the web app:

```ts
const inventory = await scan({
  patterns: ['tests/**/*.spec.ts'],
  framework: 'playwright',
  root: 'apps/trading-web',
  ignore: ['tests/legacy/**'],
});

const skipped = inventory.tests.filter((test) => test.isSkipped && !test.isConditional);
console.log(`${skipped.length} tests are always skipped`);
```

## scanSource

Scans the code of one file without reading anything from disk. Use it in editors, linters or tests.

```ts
/**
 * Scans the code of one test file, without reading anything from disk.
 *
 * Throws a `TypeError` for invalid options. Problems in the code itself are reported as diagnostics.
 * A custom `test` object imported from a local file can't be followed here; use `scan()` for that.
 */
export function scanSource(options: ScanSourceOptions): Inventory;

export interface ScanSourceOptions {
  code: string;
  /** Path of the file from the project root, used in the output and in ids. */
  relativeFilePath: string;
  framework: Framework;
  /** The framework version whose rules apply. The newest rules apply when it is missing. */
  frameworkVersion?: string | null;
  /** Which tests get the comments above them. Defaults to `non-active`. */
  comments?: CommentsMode;
  /**
   * One test or describe per case of a `.each` or `.for` table and per pass of a loop whose values the scan can work
   * out, each with the title the runner gives it. Defaults to `false`: one record per declaration.
   */
  expandCases?: boolean;
}
```

To read the state of a test from code that is not on disk:

```ts
const inventory = scanSource({
  code: "import { test } from 'vitest';\ntest.todo('charges the daily borrow fee');",
  relativeFilePath: 'tests/orders/short-selling.test.ts',
  framework: 'vitest',
  frameworkVersion: '5.0.3',
});
inventory.tests[0].state; // 'todo'
```

Because it reads no files, `scanSource` cannot follow a custom `test` object imported from a fixtures file. Tests
that use one are reported with an `unresolved-test-import` diagnostic; `scan` follows the import.

## filterInventory

Keeps the tests that pass a filter, as the [filter options](/guide/cli#filters) on the command line do. The result is
an inventory of those tests, which still matches the JSON Schema.

```ts
/**
 * Keeps the tests that pass every condition of the filter; a list keeps a test that has any of its values. The
 * result describes only those tests: their files, the describes around them, their diagnostics, and a summary
 * counted over them. Files without any tests stay, with their diagnostics, since tests may be missing from them.
 * `summary.fileCount` stays the number of files scanned.
 *
 * Throws a `TypeError` for an invalid filter.
 */
export function filterInventory(inventory: Inventory, filter: InventoryFilter): Inventory;

export interface InventoryFilter {
  /** Keeps tests in one of these states. */
  states?: TestState[];
  /** Keeps tests with one of these tags, as the output writes them. */
  tags?: string[];
  /** Keeps tests whose `fullName` matches this regular expression, ignoring case, as Playwright's `--grep` does. */
  grep?: string;
  /** Keeps tests that use `.only`, or are inside a describe that does. */
  only?: boolean;
  /** Keeps non-active tests without a reason, including expected failures and conditional states; excludes notLoaded. */
  withoutReason?: boolean;
  /**
   * Keeps the tests a change to one of these files can affect: those whose `dependencies` include it, and those that
   * reach a matching module glob or code the scan can't follow (`hasUnfollowedDependencies`). Paths are from the project root, as
   * `dependencies` writes them. An empty list keeps only the tests the scan can't follow.
   */
  related?: string[];
}
```

To list the smoke tests that are marked fixme, with their files:

```ts
const inventory = await scan({ patterns: ['tests/**/*.spec.ts'], framework: 'playwright' });
const fixme = filterInventory(inventory, { states: ['fixme'], tags: ['@smoke'] });

for (const test of fixme.tests) console.log(`${test.relativeFilePath}:${test.lineStart} ${test.fullName}`);
```

## pickTestFields

Keeps only `id` and the given keys on each test, as `--fields` does, to make the output smaller. TypeScript knows
which keys are left.

```ts
/**
 * Leaves only `id` and the given keys on each test record, in that order, to make the output smaller. Suites,
 * diagnostics and the summary are unchanged. The result no longer matches the JSON Schema, which requires every key.
 *
 * Throws a `TypeError` for a key that test records don't have.
 */
export function pickTestFields<K extends keyof TestRecord>(
  inventory: Inventory,
  fields: readonly K[],
): PickedInventory<K>;

/** An inventory whose test records have only `id` and the keys picked with `pickTestFields()`. */
export type PickedInventory<K extends keyof TestRecord> = Omit<Inventory, 'tests'> & {
  tests: Pick<TestRecord, 'id' | K>[];
};
```

```ts
const short = pickTestFields(fixme, ['fullName', 'reason']);
short.tests[0].reason; // string | null
```

## runCommands

The command lines that run the tests an inventory keeps, as `--format commands` prints them: one for each config, and
for Cypress one for each testing type, with the projects that run the tests. See
[Commands that run the tests](/guide/cli#commands-that-run-the-tests) for how each runner takes the files.

```ts
/**
 * The commands that run the tests an inventory keeps, as after `filterInventory()` with `related`: one for each config,
 * and for Cypress one for each testing type, with the projects that run the tests, sorted by config. A test whose
 * projects are unknown runs in every project of its config.
 */
export function runCommands(inventory: Inventory): RunCommand[];

/** A command line that runs some test files of an inventory with their runner, config and projects. */
export interface RunCommand {
  /** The config the files run with, from the project root; null when the scan found none. */
  config: string | null;
  /** The projects of the config that run the files, as the command selects them; `[]` to run every project. */
  projects: string[];
  /** The test files, sorted. */
  files: string[];
  /** The command line, to run from the project root in a POSIX shell. */
  command: string;
  /** What the command runs beyond `files` or why it can't run them as it is; null otherwise. */
  caveat: string | null;
}
```

To run the tests a change to the orders blotter can affect:

```ts
const affected = filterInventory(inventory, { related: ['pages/orders-blotter.ts'] });
for (const { command, caveat } of runCommands(affected)) console.log(caveat ?? '', command);
```

## diffInventories

Compares two complete saved inventories, matching tests by id and body hash. See [Compare inventories](/guide/diff)
for matching rules, change categories, hash compatibility and incomplete-scan warnings.

```ts
/**
 * Compares complete inventories without mutating them. Match ids first, then mutually unique body hashes, narrowing
 * ambiguous hashes by file, suite and dependencies. Remaining ambiguities stay additions and removals. Hashes from
 * different tool versions are not compared; scan both revisions with one version for rename and body detection.
 */
export function diffInventories(before: Inventory, after: Inventory): InventoryDiff;

/** The deterministic comparison of two saved inventories. */
export interface InventoryDiff {
  schemaVersion: 1;
  tool: Tool;
  framework: Framework;
  beforeToolVersion: string;
  afterToolVersion: string;
  hashesComparable: boolean;
  /** Category counts overlap; changed counts matched tests, while unchanged counts matches with no changes. */
  summary: Record<ChangeKind | 'changed' | 'unchanged', number>;
  changes: TestChange[];
  clones: { before: CloneGroup[]; after: CloneGroup[] };
  warnings: string[];
}

/** One addition, removal or changed test. Locations and records come from the saved scans unchanged. */
export type TestChange = {
  kinds: ChangeKind[];
  /** Changed record keys, excluding locations and ids. Hashes are included only when comparable. */
  changedFields: (keyof TestRecord)[];
} & (
  | { match: MatchMethod; before: TestRecord; after: TestRecord }
  | { match: null; before: TestRecord; after: null }
  | { match: null; before: null; after: TestRecord }
);

/** Changes a comparison can report; one matched test can have several. */
export type ChangeKind =
  | 'added'
  | 'removed'
  | 'moved'
  | 'renamed'
  | 'bodyChanged'
  | 'dependenciesChanged'
  | 'newlySkipped'
  | 'reEnabled'
  | 'stateChanged'
  | 'tagsChanged'
  | 'metadataChanged';

/** The evidence that two records identify the same test; null for an addition or removal. */
export type MatchMethod = 'id' | 'bodyHash' | 'bodyHashAndFile' | 'bodyHashAndSuite' | 'bodyHashAndDependencies';

/** Tests with identical syntax-tree bodies, including trivial bodies; this does not prove they test the same thing. */
export interface CloneGroup {
  bodyHash: string;
  testIds: string[];
}
```

Read complete scans saved with the same version and scan options, then compare them:

```ts
import { readFileSync } from 'node:fs';
import { diffInventories, formatDiffMarkdown, type Inventory } from 'test-inventory';

const before: Inventory = JSON.parse(readFileSync('inventories/base.json', 'utf8'));
const after: Inventory = JSON.parse(readFileSync('inventories/head.json', 'utf8'));
const diff = diffInventories(before, after);

console.log(diff.summary.newlySkipped);
console.log(diff.warnings);
console.log(formatDiffMarkdown(diff));
```

The comparison validates the inventories at runtime. A TypeScript annotation on parsed JSON is not validation.

## formatDiffMarkdown

Formats a diff as a Markdown summary and table. Titles and paths are escaped as text.

```ts
/** A report ready to save as Markdown or use as the body of a pull request comment. */
export function formatDiffMarkdown(diff: InventoryDiff): string;
```

## Inventory

Both scan functions return an inventory, the object the command line writes as JSON. The
[output reference](/reference/output) describes each of its records key by key.

```ts
/** The output of one scan. */
export interface Inventory {
  /** Version of this format. It changes only when a key is removed, renamed or changes meaning. */
  schemaVersion: 1;
  tool: Tool;
  /** The framework the scan was run for. */
  framework: Framework;
  /** Read from the project, or given with `--framework-version`; null when unknown. */
  frameworkVersion: string | null;
  summary: Summary;
  /** The configs the scanned files use, sorted by path. */
  configs: ConfigRecord[];
  /** One per scanned file, in the order the files were scanned. */
  files: FileRecord[];
  suites: SuiteRecord[];
  tests: TestRecord[];
  diagnostics: Diagnostic[];
}

export interface Tool {
  name: 'test-inventory';
  /** Version of test-inventory that produced the output. */
  version: string;
}
```

## Errors

Every function throws a `TypeError` that names the option when an option is invalid. Anything about the scanned code
or files becomes a [diagnostic](/reference/diagnostics) in the result. A scan whose `signal` aborts rejects with the
signal's `reason`, as `fetch` does.

## JSON Schema

The output's JSON Schema ships with the package, under the `schemaVersion` it describes, so a reader can pin the
version of the format it understands:

```ts
import schema from 'test-inventory/schema/v1.json' with { type: 'json' };
import diffSchema from 'test-inventory/schema/diff-v1.json' with { type: 'json' };
```

It is also published at [huldoser.github.io/test-inventory/schema/v1.json](https://huldoser.github.io/test-inventory/schema/v1.json),
the URL in its `$id`. The diff schema is published at
[schema/diff-v1.json](https://huldoser.github.io/test-inventory/schema/diff-v1.json).
