百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

tsnapi

> 测试质量
开源

图书馆公共 API 快照测试,用于测试运行时导出和类型声明。

194 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

图书馆公共 API 快照测试,用于测试运行时导出和类型声明。

tsnapi

Library public API snapshot testing for runtime exports and type declarations.

Captures your public API surface -- both runtime exports and type declarations -- into human-readable snapshot files that you commit alongside your code. When the API changes unexpectedly, you'll know.

Think of it like Vitest's snapshot testing, but for your package's public contract.

For example, you can check the generated snapshots for the package itself: __snapshots__/tsnapi.

Why

When maintaining a library, it's easy to accidentally:

  • Remove or rename an export
  • Change a function signature
  • Break type declarations
  • Introduce unintended public API surface

tsnapi makes these changes visible in your git diff. Every build produces a pair of snapshot files per entry point:

  • .snapshot.js -- what your package exports at runtime
  • .snapshot.d.ts -- what your package exports as types

These files are committed to your repo. When they change, you review the diff -- just like any other code change.

Install

bash
pnpm add -D tsnapi

Usage

As a Rolldown / tsdown plugin

The most recommended way of using tsnapi is to use it with tsdown -- an elegant library bundler built on top of Rolldown:

typescript
// tsdown.config.ts
import { defineConfig } from 'tsdown'
import ApiSnapshot from 'tsnapi/rolldown'

export default defineConfig({
  entry: ['src/index.ts'],
  dts: true,
  plugins: [
    ApiSnapshot()
  ],
})

On first build, snapshot files are written. On subsequent builds, the plugin compares against existing snapshots and fails the build with a diff if the API changed.

To update snapshots when you intentionally change the API, set the update option to true or use the --update-snapshot / -u CLI flag:

bash
tsdown --update-snapshot
# or
UPDATE_SNAPSHOT=1 tsdown

or add the update option to the plugin:

typescript
plugins: [
  ApiSnapshot({ update: true })
],

Breaking changes guard

When you update snapshots, tsnapi classifies the change as either additive or breaking. A breaking change aborts the update without overwriting the snapshot, so you can't silently ship a breaking API change with a routine -u:

Breaking API changes detected

  index
    - removed   createServer
    ~ narrowed  RequestOptions

  Refusing to update snapshots because the public API changed in a breaking way.
  If this is intentional, re-run with --allow-breaking (or set TSNAPI_ALLOW_BREAKING=1).

The check is deliberately lossy — it favours not blocking a change to avoid false positives, while reliably catching the important case: something being removed. A change is treated as breaking only when a declaration loses something. Purely additive changes are allowed straight through:

Change Classified as
Removing an export breaking
Removing an interface member, parameter, or union arm breaking
Replacing a type with an unrelated one (e.g. string → number) breaking
Adding a new export additive
Adding a new interface property additive
Widening a parameter or return type with a union (e.g. string → string | number) additive
Adding a parameter additive

Because the guard only checks that nothing was removed, some genuinely breaking changes (for instance, widening a return type, which callers may not expect) are intentionally allowed through to keep false positives low. A normal comparison build still fails on any change, so every change is always visible in your git diff regardless.

When the change really is intentional, opt out with the --allow-breaking CLI flag, the TSNAPI_ALLOW_BREAKING=1 environment variable, or the allowBreaking plugin option:

bash
tsnapi -u --allow-breaking
# or
UPDATE_SNAPSHOT=1 TSNAPI_ALLOW_BREAKING=1 tsdown
typescript
plugins: [
  ApiSnapshot({ update: true, allowBreaking: true })
],

Note: The guard only runs while updating. A normal comparison build still fails on any change (additive or breaking) so every change lands in your git diff.

As a CLI

Snapshot any package's dist without a bundler:

bash
# Snapshot the current package (reads package.json exports → parses dist files), which you need to run the build first to generate the dist
tsnapi

# Update snapshots when you intentionally change the API
tsnapi -u

# Allow a breaking API change (removed/changed export) while updating
tsnapi -u --allow-breaking

Interactive inspector (tsnapi ui)

Visualize the public API of every package in a workspace as an interactive graph, and trace how it changed between two git refs. Built on devframe and @antfu/design.

bash
# Launch the inspector for the current workspace (reads committed snapshots — generate/update them first)
tsnapi ui

# Diff two refs / the working tree from the CLI, then explore in the browser
#   — the picker lets you pick Base/Compare (working tree, HEAD, branch, tag, sha)

# Export a self-contained static build (single current state)
tsnapi ui build --out-dir dist-inspector

# Bake a shareable, read-only diff between two refs
tsnapi ui build --base v1.1.0 --compare HEAD --out-dir dist-inspector

The tree runs workspace → package → entry → member, each member coloured by kind and by diff status — added / removed / modified (narrowed) / widened — reusing tsnapi's own breaking-change analysis. The inspector only ever reads already-generated __snapshots__ files, never regenerates them itself: historical refs are read straight from the committed snapshot via git show, and the working-tree side reads whatever snapshot currently sits on disk (uncommitted edits included). Run tsnapi/tsnapi -u (or your Vitest snapshot tests) to (re)generate a snapshot before inspecting it.

With Vitest

tsnapi/vitest provides higher-level Vitest integration that uses toMatchFileSnapshot to store snapshots as individual files.

Note: tsnapi reads built dist files, so make sure to build your packages before running the tests. We recommend updating your test script to build first:

json
{
  "scripts": {
    "test": "pnpm run build && vitest"
  }
}

If you are using tsdown, you can use tsdown-stale-guard to set up the build guard automatically.

Single package

typescript
// api.test.ts
import { fileURLToPath } from 'node:url'
import { snapshotApiPerEntry } from 'tsnapi/vitest'
import { describe } from 'vitest'

const dir = fileURLToPath(new URL('../packages/my-lib', import.meta.url))

describe('my-lib API', async () => {
  await snapshotApiPerEntry(dir)
})

This creates it() blocks for each entry point, asserting both runtime and DTS snapshots. Snapshot files are written to __snapshots__/tsnapi// relative to the test file. Run vitest -u to update snapshots when you intentionally change the API.

Breaking changes guard

The same breaking changes guard applies here. Running vitest -u would normally overwrite the snapshot files unconditionally; tsnapi intercepts the update, classifies the change, and fails the test without overwriting the snapshot when an export was removed or narrowed:

Breaking API changes detected

  index
    - removed   parseConfig

Because Vitest's CLI rejects unknown flags, the --allow-breaking flag can't be passed through vitest. Opt out with the TSNAPI_ALLOW_BREAKING=1 environment variable or the allowBreaking option instead:

bash
# Allow a breaking API change while updating
TSNAPI_ALLOW_BREAKING=1 vitest -u
typescript
await snapshotApiPerEntry(dir, { allowBreaking: true })
// or, for monorepos
await describePackagesApiSnapshots({ allowBreaking: true })

Note: The guard only runs while updating (-u). A normal comparison run already fails on any change (additive or breaking), so every change stays visible in your git diff.

Monorepo

For monorepos, describePackagesApiSnapshots creates a describe() block per package. When packages is omitted, it auto-discovers workspace packages from pnpm-workspace.yaml or the workspaces field in package.json:

typescript
// api.test.ts
import { describePackagesApiSnapshots } from 'tsnapi/vitest'

// Auto-discovers all workspace packages
await describePackagesApiSnapshots()

Or provide explicit package paths:

typescript
import { fileURLToPath } from 'node:url'
import { describePackagesApiSnapshots } from 'tsnapi/vitest'

await describePackagesApiSnapshots({
  packages: [
    fileURLToPath(new URL('../packages/core', import.meta.url)),
    fileURLToPath(new URL('../packages/utils', import.meta.url)),
  ],
})

describePackagesApiSnapshots accepts filter, beforeEach, and afterEach callbacks. Each receives a PackageContext object:

typescript
interface PackageContext {
  cwd: string // the input cwd
  workspaceRoot: string // the resolved workspace root
  packageRoot: string // absolute path to the package directory
  packageName: string // package name from package.json
  outputDir: string // snapshot output directory (relative to test file)
}

filter

Called for each discovered package. The context is mutable — modify any property to customize behavior. Return false to skip the package entirely:

typescript
import { describePackagesApiSnapshots } from 'tsnapi/vitest'

await describePackagesApiSnapshots({
  filter(ctx) {
    // Skip private packages
    if (ctx.packageName.startsWith('@internal/'))
      return false
    // Strip org scope from describe block name
    ctx.packageName = ctx.packageName.replace(/^@.*\//, '')
    // Customize snapshot output directory per package
    ctx.outputDir = `__snapshots__/${ctx.packageName}`
  },
})

beforeEach / afterEach

Lifecycle hooks registered inside each package's describe block via Vitest's beforeEach/afterEach. They receive the (possibly mutated) context:

typescript
import { describePackagesApiSnapshots } from 'tsnapi/vitest'

await describePackagesApiSnapshots({
  beforeEach({ packageRoot, packageName }) {
    console.log(`Testing ${packageName} at ${packageRoot}`)
  },
  afterEach({ packageName }) {
    console.log(`Done testing ${packageName}`)
  },
})

For example, if you use tsdown-stale-guard, you can use the beforeEach hook to guard against stale builds — ensuring each package's dist is in sync with its source before running snapshot tests:

typescript
import { guardStaleBuild } from 'tsdown-stale-guard'
import { describePackagesApiSnapshots } from 'tsnapi/vitest'

await describePackagesApiSnapshots({
  async beforeEach({ packageRoot }) {
    // guard will throw if the build is stale to fail the test
    await guardStaleBuild({ root: packageRoot })
  },
})

Run vitest -u to update snapshots when you intentionally change the API.

Per-entry hooks

Three hooks let you intervene per entry point, at increasing depth. They live on ApiSnapshotOptions, so they work with snapshotApiPerEntry, describePackagesApiSnapshots, generateApiSnapshot, the CLI helpers, and the rolldown plugin alike.

entryFilter skips entries entirely — useful when a package exports large default-data objects (themes, color palettes) that are low-signal for an API guard:

typescript
import { describePackagesApiSnapshots } from 'tsnapi/vitest'

await describePackagesApiSnapshots({
  entryFilter: ({ packageName, entryName }) =>
    entryName !== './theme' && entryName !== './colors',
})

transformEntries modifies the structural representation before it is serialized: each snapshot surface is a list of entries ({ name, kind, text } — one per export or referenced declaration). Mutate the a

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptsnapshotsnapshot-testing

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类测试质量
定价开源

> 相关工具

J
Jest
JavaScript 测试框架
P
Playwright
现代端到端测试框架
E
eslint-plugin-test-selectors
Enforces that data-test-id attributes are added to interactive DOM elements (JSX) to help with UI testing. JSX only.