On this page
deno test
Deno 自带一个内置测试运行器,使用
Deno.test() API。要了解如何编写测试,请参阅
测试基础指南。有关断言,请参阅
@std/assert 和
@std/expect。
运行测试 Jump to heading
运行当前目录及其子目录中的所有测试:
deno test
运行特定文件中的测试:
deno test src/fetch_test.ts src/signal_test.ts
运行匹配 glob 模式的测试:
deno test src/*.test.ts
跳过类型检查:
deno test --no-check
过滤 Jump to heading
仅运行名称与字符串或使用 --filter 的模式匹配的测试:
# 运行名称包含 "database" 的测试
deno test --filter "database"
# 运行名称匹配正则表达式的测试
deno test --filter "/^connect.*/"
用正斜杠 (/) 将过滤值括起来,以将其视为正则表达式,类似于 JavaScript 的正则字面量语法。过滤不会影响测试步骤:当某个测试名称与过滤条件匹配时,它的所有步骤都会运行。
若要控制最初收集哪些测试文件,可在配置文件中设置 test.include 和 test.exclude。请参阅
包含与排除。
运行受影响的测试 Jump to heading
在迭代修改时,你可以只运行受其影响的测试,而不是 整个测试套件。这些都是一次性运行,不是 watch 模式。
--changed 会运行受 git 中已更改文件影响的测试模块。若不提供
值,它会使用工作区(已暂存、未暂存和未跟踪的文件);传入一个
引用也可以包含自该引用与当前分支 merge-base 以来的提交:
# 受未提交更改影响的测试
deno test --changed
# 自从从 main 分支切出以来受影响的测试
deno test --changed=origin/main
--related 会运行依赖于特定源文件的测试模块,而不
查询 git:
# 导入 src/util.ts 的测试
deno test --related=src/util.ts
这两个标志都会将收集到的测试文件筛选为那些通过模块图 到达已更改文件或命名文件的测试文件。有关工作流以及选择如何 生效,请参阅测试指南中的 运行受影响的测试。
权限 Jump to heading
测试会以与 deno run 相同的权限模型运行。
为你的测试套件授予权限:
deno test --allow-read --allow-net
监听模式 Jump to heading
在文件更改时自动重新运行测试:
deno test --watch
并行执行 Jump to heading
在多个 worker 线程之间运行测试文件:
deno test --parallel
默认情况下,--parallel 使用可用 CPU 的数量。使用 DENO_JOBS=<N>
来控制线程数量:
DENO_JOBS=4 deno test --parallel
代码覆盖率 Jump to heading
收集覆盖率数据并生成报告:
deno test --coverage
这会将原始覆盖率数据写入 coverage/ 目录。要基于已有的覆盖率数据生成摘要,
请使用
deno coverage:
deno coverage coverage/
你也可以输出 lcov 报告以供外部工具使用:
deno coverage --lcov coverage/ > coverage.lcov
要在覆盖率低于目标值时使运行失败,请设置阈值(例如
deno coverage --threshold=90)。有关按指标配置,请参见
coverage thresholds。
参数化测试 Jump to heading
使用 Deno.test.each 在一组用例表上运行相同的测试主体,它会为每个用例分别注册一个独立报告的测试。有关名称模板和用例形式,请参见参数化测试。
快照测试 Jump to heading
捕获一个值,并在每次运行时将其与存储的参考值进行比较,使用内置的 t.assertSnapshot,并通过 --update-snapshots(-u)进行更新。参见
快照测试。
报告器 Jump to heading
使用 --reporter 选择输出格式。内置了四种报告器:
pretty(默认):详细、易读的输出dot:每个测试显示一个字符,便于快速概览junit:JUnit XML 格式,供 CI 系统使用tap:Test Anything Protocol 输出
deno test --reporter=dot
deno test --reporter=tap
在终端中保留人类可读的 pretty 输出的同时,将 JUnit XML 报告写入文件:
deno test --junit-path=report.xml
随机化顺序 Jump to heading
打乱测试运行顺序,以发现测试之间隐藏的依赖关系:
deno test --shuffle
分片 Jump to heading
使用 --shard=<index>/<count> 将测试套件拆分到多台机器上,其中
index 从 1 开始。已发现的测试文件会按稳定顺序排序,并
划分为 <count> 个平衡分组;运行时只执行第 <index> 组中的文件:
# 在 3 台机器中的第 1 台上
deno test --shard=1/3
# 在 3 台机器中的第 2 台上
deno test --shard=2/3
分片会在 --shuffle 之前应用,因此无论随机种子如何,同一个分片在
每台机器上都会运行相同的文件。
重试和重复 Jump to heading
使用 --retry 和 --repeats 为整个运行设置默认的重试和重复次数:
# 每个失败的测试在报告失败前最多重新运行两次
deno test --retry=2
# 每个测试运行三次,如果任何一次运行失败则判定失败
deno test --repeats=3
设置了自己的 retry 或 repeats 选项的测试会覆盖该标志。有关每个测试的选项,请参见重试和重复测试。
泄漏检测 Jump to heading
追踪泄漏的异步操作、计时器或资源的来源:
deno test --trace-leaks
在文档中测试代码 Jump to heading
将 JSDoc 和 Markdown 文件中的代码块作为测试执行:
deno test --doc
有关详情,请参阅文档测试。
deno test [OPTIONS] [files]... [-- [SCRIPT_ARG]...]Run tests using Deno's built-in test runner.
Evaluate the given modules, run all tests declared with Deno.test() and report results to standard output:
deno test src/fetch_test.ts src/signal_test.ts
Directory arguments are expanded to all contained files matching the glob {*_,*.,}test.{js,mjs,ts,mts,jsx,tsx}
or **/__tests__/**:
deno test src/
Type checking options Jump to heading
--check<CHECK_TYPE>optionalSet type-checking behavior. This subcommand type-checks local modules by default, so passing --check is redundant; pass --check=all to also type-check remote modules. Alternatively, use the 'deno check' subcommand.
--no-check<NO_CHECK_TYPE>optionalSkip type-checking. If the value of "remote" is supplied, diagnostic errors from remote modules will be ignored.
Dependency management options Jump to heading
--cached-onlyRequire that remote dependencies are already cached.
--frozen<BOOLEAN>optionalError out if lockfile is out of date.
Load import map file from local file or remote URL.
--lock<FILE>optionalCheck the specified lock file. (If value is not provided, defaults to "./deno.lock").
--no-lockDisable auto discovery of the lock file.
--no-npmDo not resolve npm modules.
--no-remoteDo not resolve remote modules.
--node-modules-dir<MODE>optionalSelects the node_modules directory mode for npm packages (not a path). One of: auto (create a local node_modules directory and install npm packages into it), manual (use the existing local node_modules directory, do not modify it), none (do not use a local node_modules directory; resolve npm packages from the global cache). Defaults to auto when the flag is passed without a value.
--node-modules-linker<MODE>Sets the linker mode for npm packages (isolated or hoisted).
--reload, -r<CACHE_BLOCKLIST>optionalReload source code cache (recompile TypeScript). With no value, reloads everything. Pass a comma-separated list of specifiers to reload only those modules; npm: reloads all npm modules; npm:chalk reloads a single npm module; jsr:@std/http/file-server,jsr:@std/assert/assert-equals reloads specific modules.
--vendor<vendor>optionalToggles local vendor folder usage for remote modules and a node_modules folder for npm packages.
Options Jump to heading
--allow-scripts<PACKAGE>optionalAllow running npm lifecycle scripts for the given packages
Note: Scripts will only be executed when using a node_modules directory (--node-modules-dir).
--cert<FILE>Load certificate authority from PEM encoded file.
--conditions<conditions>Use this argument to specify custom conditions for npm package exports. You can also use DENO_CONDITIONS env var. .
Configure different aspects of deno including TypeScript, linting, and code formatting.
Typically the configuration file will be called deno.json or deno.jsonc and
automatically detected; in that case this flag is not necessary.
--env-file<FILE>optionalLoad environment variables from local file Only the first environment variable with a given key is used. Existing process environment variables are not overwritten, so if variables with the same names already exist in the environment, their values will be preserved. Where multiple declarations for the same environment variable exist in your .env file, the first one encountered is applied. This is determined by the order of the files you pass as arguments.
--ext<ext>Set content type of the supplied file.
--hide-stacktracesHide stack traces for errors in failure test results.
--ignore<ignore>Ignore files.
--location<HREF>Value of globalThis.location used by some web APIs.
--minimum-dependency-age<minimum-dependency-age>(Unstable) The age in minutes, ISO-8601 duration or RFC3339 absolute timestamp (e.g. '120' for two hours, 'P2D' for two days, '2025-09-16' for cutoff date, '2025-09-16T12:00:00+00:00' for cutoff time, '0' to disable).
--no-configDisable automatic loading of the configuration file.
--parallelRun test modules in parallel. Parallelism defaults to the number of available CPUs or the value of the DENO_JOBS environment variable.
--preload<FILE>A list of files that will be executed before the main module.
--require<FILE>A list of CommonJS modules that will be executed before the main module.
--seed<NUMBER>Set the random number generator seed.
--v8-flags<V8_FLAGS>optionalTo see a list of all available flags use --v8-flags=--help
Flags can also be set via the DENO_V8_FLAGS environment variable.
Any flags set with this flag are appended after the DENO_V8_FLAGS environment variable.
Debugging options Jump to heading
--inspect<HOST_PORT>optionalActivate inspector on host:port [default: 127.0.0.1:9229]. Host and port are optional. Using port 0 will assign a random free port.
--inspect-brk<HOST_PORT>optionalActivate inspector on host:port, wait for debugger to connect and break at the start of user script.
--inspect-wait<HOST_PORT>optionalActivate inspector on host:port and wait for debugger to connect before running user code.
Testing options Jump to heading
--changed<REF>optionalRun only test modules affected by files changed in git.
With no value, uses uncommitted changes (staged, unstaged and untracked).
Pass a git ref to compare against, e.g. --changed=main or --changed=HEAD~1.
--cleanEmpty the temporary coverage profile data directory before running tests.
Note: running multiple deno test --clean`` calls in series or parallel for the same coverage directory may cause race conditions.
--coverage<DIR>optionalCollect coverage profile data into DIR. If DIR is not specified, it uses 'coverage/'. This option can also be set via the DENO_COVERAGE_DIR environment variable.
--coverage-raw-data-onlyOnly collect raw coverage data, without generating a report.
--coverage-threshold<PERCENT>Fail if coverage is below this percentage (0-100). Requires --coverage.
--docEvaluate code blocks in JSDoc and Markdown.
--fail-fast<N>optionalStop after N errors. Defaults to stopping after first failure.
--filter<filter>Run tests with this string or regexp pattern in the test name.
--junit-path<PATH>Write a JUnit XML test report to PATH. Use '-' to write to stdout which is the default when PATH is not provided.
--no-runCache test modules, but don't run tests.
--permit-no-filesDon't return an error code if no files were found.
--repeats<NUMBER>Run each test NUMBER additional times. Every repetition must pass. Tests that set their own repeats option take precedence.
--reporter<reporter>Select reporter to use. Default to 'pretty'.
--retry<NUMBER>Re-run failing tests up to NUMBER times. A test passes if any attempt passes. Tests that set their own retry option take precedence.
--sanitize-opsEnable the ops sanitizer, which ensures that all async ops started in a test are completed before the test ends.
--sanitize-resourcesEnable the resources sanitizer, which ensures that all resources opened in a test are closed before the test ends.
--shard<INDEX/COUNT>Run only the test files for shard INDEX of COUNT, e.g. --shard=2/3.
The discovered test files are sorted and split into COUNT consecutive groups; INDEX is 1-based. Useful for splitting a run across machines.
--shuffle<NUMBER>optionalShuffle the order in which the tests are run.
--trace-leaksEnable tracing of leaks. Useful when debugging leaking ops in test, but impacts test execution time.
--update-snapshots, -uUpdate snapshots created with t.assertSnapshot() instead of failing when they do not match.
File watching options Jump to heading
--no-clear-screenDo not clear terminal screen when under watch mode.
--watch<FILES>optionalWatch for file changes and restart process automatically. Local files from entry point module graph are watched by default. Additional paths might be watched by passing them as arguments to this flag.
--watch-exclude<FILES>optionalExclude provided files/patterns from watch mode.