@approval-tests/approvals

中文文档
7.5.14发布于 2026/11/02Apache-2.0TypeScriptCommonJS构建来源已验证近 30 天下载 2.3万

Approval Tests Library - Capturing Human Intelligence

原始使用文档
文档目录31 节
  1. Contents
  2. Intro
  3. Badges
  4. Integrations
  5. Getting Started
  6. Jest Typescript Starter Project
  7. Mocha
  8. Documentation
  9. CLI
  10. Install Approvals CLI
  11. CLI Help
  12. Reporters
  13. Built-In Reporters
  14. Supported Diff Tools
  15. Custom Reporter
  16. Configuration
  17. API
  18. approvals
  19. approvals.reporters
  20. approvals~configure(overrideOptions)
  21. approvals~getConfig(overrideOptions) ⇒ Object
  22. approvals~mocha(optionalBaseDir)
  23. approvals~verifyAndScrub(dirName, testName, data, scrubber,…
  24. approvals~verify(dirName, testName, data, optionsOverride)
  25. approvals~verifyAsJSON(dirName, testName, data, optionsOver…
  26. approvals~verifyAsJSONAndScrub(dirName, testName, data, scr…
  27. approvals~verifyWithControl(namer, writer, [reporterFactory…
  28. Source Control
  29. Git
  30. Contributing
  31. License

Approvals (Approval Tests for Node.js)

Contents

Intro

Approval Tests Library - Capturing Human Intelligence

What is an approval test? Check out a brief overview here or learn more about Approvals at approvaltests.com.

Badges

ServiceStatus
Package@approval-tests/approvals on npm
Github (Linux, Mac, Windows)Build & Test

Integrations

Getting Started

Mocha, Jest, and Vitest are optional peer dependencies. Install the framework your tests use alongside Approvals. Approvals silently skips integrations for frameworks that are not installed.

Jest Typescript Starter Project

If you want to jump start a new project, clone the Jest Starter Project

Mocha

Below is a simple getting started using Mocha.

  1. Create a project (folder)

    mkdir MyProject
    cd MyProject
    
  2. Install approvals

    npm install --save-dev @approval-tests/approvals
    
  3. Install Mocha in the project to execute our tests

    npm install --save-dev mocha
    
  4. Create a sample Mocha test file called SimpleLogger.test.js.

    require("@approval-tests/approvals").mocha();
    
    describe("When running some tests", function () {
      it("should be able to use Approvals", function () {
        var data = "Hello World!";
        this.verify(data); // or this.verifyAsJSON(data)
      });
    });
    
  5. Test the file with mocha.

    npx mocha SimpleLogger.test.js
    
  6. You should be presented with a diff tool. (if not, you may need to install one?)

Documentation

If using Jest, see more documentation here.

CLI

Approvals.NodeJS has a version that can be run as a command line tool.

You can check out the Examples section of the below CLI help. Or a blog post introducing the tool here: Approval Tests - Command Line Tool (CLI).

Install Approvals CLI

npm install -g @approval-tests/approvals

CLI Help

By running approvals --help

Usage

approvals testName [options]

ArgDescription
[-f | --forceapproveall]Skip the approve step and apply the results to the .approved.txt file (good for a first time run)
[--reporter difftool]supports multiple EX: --reporter opendiff --reporter gitdiff
[--outdir]dir to place approval file - defaults to current directory
[--verbose]extra debug info
TODO:We need to extend the supported args to include other approval options. (file an issue if you need one that's not here)

Examples

Simple hello world
echo 'Hello World!' | approvals helloWorldTest
Specify diff reporter (great for C.I.)
echo 'Hello World!' | approvals helloWorldTest --reporter gitdiff
Multiple diff reporters
echo 'Hello World!' | approvals helloWorldTest --reporter gitdiff --reporter p4merge

Reporters

Built-In Reporters

Any of the following reporter may suite your needs. Some support images, some only diffing text, some on mac and linux, some only on windows... Feel free to configure the system to automatically choose your favorite.

Supported Diff Tools

approval nameProgramWindowsMac/LinuxNotes
beyondcompareBeyond Compare✓✓
copycommandgit diff (console diff)✓✓Great for C.I. builds runs.
diffmergeDiffMerge✓✓
donothing✓✓This one does what it says - nothing.
gitdiffgit diff (console diff)✓✓Using git cli to diff files. Useful in C.I. builds
icdiffIcdiff✓✓
kdiff3KDiff3✓✓
kompareKompare?✓
meldMeld✓✓
multi✓✓This allows you to run multiple reporters at the same time. EX: when verifying images, you might like to use p4merge along with the copycommand reporter to get the copy CLI command to approve an image as well as view the diff in a tool.
nodediffnodediff (console diff)✓✓colorized CLI output without a popup of a diff tool
opendiffopendiff✓
p4mergep4merge✓✓
tortoisemergeTortise merge✓✓
vimdiff✓✓
visualstudioVisual Studio Diff tool✓
vscodeVisual Studio Code Diff tool✓✓
vscodiumVSCodium Diff tool✓✓

Custom Reporter

Along with the built-in reporters, you can create your own custom reporter just by taking this sample and filling out the interface with your custom reporters desired behavior.

    /* OR a custom reporter object. Below is an example custom reporter */
    {
      /**
       * Determine if the file that needs to be reported on can be handled by this reporter object.
       * @param {string} receivedFilePath - The path to a received file.
       */
      canReportOn(receivedFilePath) {
        return true;
      }

      /**
       * Apply the logic necessary to report a difference.
       *  EX:
       *     - Open a diff program using the approved & received files
       *     - Generate and email a report showing the differences.
       * @param {string} approvedFilePath - The path to an approved file.
       * @param {string} receivedFilePath - The path to a received file.
       */
      // Actually execute the diff against the two files
      report(approvedFilePath, receivedFilePath) {
        // Do some reporting.
        // Typically by launching a diff tool
      }
    }

Configuration

Or more, controlling the behavior of approvals through various tweaks to configuration.

Approvals uses the below configuration to drive its behavior. How you communicate that configuration to approvals can happen in several ways.

The default configuration as defined below can be overridden by using the following strategy.

NOTE: Priority/order of config selection comes from the below list where the first item have the defined defaults and each next step having a potential to override the previous if a configuration value is specified.

  1. Starting with the defaults (as shown in the JS object below) this is defined in lib/config.ts.
  2. We then take and override the defaults (and only the properties specified) with config in a yaml or json file in your home directory ~/.approvalsConfig.
  3. You can then call approvals.configure({...}).
  4. Then passing any specific configuration at the test level as the last parameter in the verify function .verify(..., {...overridden config...});. See API for specific parameters.

Here's an example of using a single reporter p4merge, and overriding whatever is configured. This will only override this specific test.

it("should use a specific reporter", function () {
  this.verify("some data", {
    reporters: ["p4merge"],
  });
});

If you have the need to execute multiple reporters on a single failure.

Say you made an "awesomeDiffReporter" and wanted it to run that in combination with a "notifyTheBossViaEmailReporter" you can use the MultiReporter like below.

var approvals = require("@approval-tests/approvals");
var MultiReporter = approvals.reporters.MultiReporter;

it("should use a multiple reporters", function () {
  this.verify("some data", {
    reporters: [new MultiReporter(["p4merge", "copycommand"])],
  });
});

export const defaultConfig: Config = {
  reporters: [
    "BeyondCompare",
    "diffmerge",
    "p4merge",
    "tortoisemerge",
    "nodediff",
    "opendiff",
    "gitdiff",
  ],
  normalizeLineEndingsTo: false,
  failOnLineEndingDifferences: false,
  appendEOL: true,
  EOL: os.EOL,
  errorOnStaleApprovedFiles: true,
  shouldIgnoreStaleApprovedFile: () => false,
  stripBOM: false,
  forceApproveAll: false,
  blockUntilReporterExits: false,
  maxLaunches: 10,
};

snippet source | anchor

API

approvals

Approvals module.

approvals.reporters

reporters gives access to the MultiReporter

Kind: static property of approvals Example

const MultiReporter = approvals.reporters.MultiReporter

reporters.MultiReporter

This allows access to the MultiReporter constructor. You can use this to run multiple reporters at the same time.

Kind: static property of reporters Example

approvals.verify(__dirname, "multi-reporter-example", "some data", {
  reporters: [
    new MultiReporter('p4merge', 'copycommand')
  ]
});

approvals~configure(overrideOptions)

Allows you to provide overrides to the default configuration.

Kind: inner method of approvals

ParamType
overrideOptions*

Example

const approvals = require('@approval-tests/approvals');
approvals.configure({
  reporters: ['p4merge']
});

approvals~getConfig(overrideOptions) ⇒ Object

Allows the creation of an approvals configuration object using any passed in options to override the defaults.

Kind: inner method of approvals Returns: Object - approvals config object with any options overridden.

ParamType
overrideOptionsObject

approvals~mocha(optionalBaseDir)

Configure approvals to hook into Mocha tests.

Kind: inner method of approvals

ParamTypeDescription
optionalBaseDir*An optional folder to save approval files to.

approvals~verifyAndScrub(dirName, testName, data, scrubber, optionsOverride)

Use this to apply the scrubber function to any data before running verify.

Kind: inner method of approvals

ParamTypeDescription
dirNamestringTypically __dirname but could be the base-directory (anywhere) to store both approved and received files.
testNamestringA file name safe string to call the file associated with this test.
datastring | BufferEither the string to save as a text file or a Buffer that represents an image
scrubber*A function that takes a string and returns a string. Approvals will call this if it exists to scrub the "data" before writing to any files.
optionsOverride*An object that can contain configurational overrides as defined in the approvals configuration object.

Example

// basic approval test with a custom scrubber
const approvals = require('@approval-tests/approvals');
const scrubber = approvals.scrubbers.multiScrubber([
   function (data) {
     return (data || '').replace("some text", "some other text");
   },
   approvals.scrubbers.guidScrubber // to remove guids from the received data
});
approvals.verifyAndScrub(__dirname, 'sample-approval-test', "some text to verify", scrubber);

approvals~verify(dirName, testName, data, optionsOverride)

Kind: inner method of approvals

ParamTypeDescription
dirNamestringTypically __dirname but could be the base-directory (anywhere) to store both approved and received files.
testNamestringA file name save string to call the file associated with this test.
datastring | BufferEither the string to save as a text file or a Buffer that represents an image
optionsOverride*An object that can contain configurational overrides as defined in the approvals configuration object.

Example

// basic approval test
const approvals = require('@approval-tests/approvals');
approvals.verify(__dirname, 'sample-approval-test', "some text to verify");

Example

// basic approval test providing an option to override configuration
const approvals = require('@approval-tests/approvals');
approvals.verify(__dirname, 'sample-approval-test', "some text to verify", { normalizeLineEndingsTo: true });

approvals~verifyAsJSON(dirName, testName, data, optionsOverride)

You can pass as "data" any javascript object to be JSON.stringified and run verify against.

Kind: inner method of approvals

ParamTypeDescription
dirNamestringTypically __dirname but could be the base-directory (anywhere) to store both approved and received files.
testNamestringA file name safe string to call the file associated with this test.
datastring | BufferThis can be any JavaScript object/array that will be JSON.stringified before running verify
optionsOverride*An object that can contain configurational overrides as defined in the approvals configuration object.

Example

const approvals = require('@approval-tests/approvals');
approvals.verifyAndScrub(__dirname, 'sample-approval-test', { a: "some text in an object" });

approvals~verifyAsJSONAndScrub(dirName, testName, data, scrubber, optionsOverride)

You can pass as "data" any javascript object to be JSON.stringified. Before we run verify the scrubber will be run against the complete string before running verify against it.

Kind: inner method of approvals

ParamTypeDescription
dirNamestringTypically __dirname but could be the base-directory (anywhere) to store both approved and received files.
testNamestringA file name safe string to call the file associated with this test.
datastring | BufferThis can be any JavaScript object/array that will be JSON.stringified before running verify
scrubber*A function that takes a string and returns a string. Approvals will call this if it exists to scrub the "data" before writing to any files.
optionsOverride*An object that can contain configurational overrides as defined in the approvals configuration object.

Example

// basic approval test with a custom scrubber
const approvals = require('@approval-tests/approvals');
const scrubber = approvals.scrubbers.multiScrubber([
   function (data) {
     return (data || '').replace("some text", "some other text");
   },
   approvals.scrubbers.guidScrubber // to remove guids from the received data
});
approvals.verifyAndScrub(__dirname, 'sample-approval-test', { a: "some text in an object" }, scrubber);

approvals~verifyWithControl(namer, writer, [reporterFactory], [optionsOverride])

This allows you to take full control of naming and writing files before verifying.

For an example that we use to generate the docs within the readme, check out the test/mocha/readmeTests.mts in this project.

Kind: inner method of approvals

ParamType
namerObject
writerObject
[reporterFactory]function
[optionsOverride]Object

Source Control

The approvals tool generates 2 files and you likely want to ignore one and check in the other.

  • *.received.* files should be IGNORED.
  • *.approved.* You'll likely want to keep the approved files in source control.

Git

If you're using Git add this to your .gitignore:

*.received.*

Depending on your operating system and your eol settings in git, the diff output on a failed test might report each line as changed because of differences in line endings. To avoid this, consider fixating eol conversion to crlf for approved files by adding this line to your .gitattributes file:

*.approved.* eol=lf

Contributing

Check out the guidelines!

License

Copyright (c) 2012-2017 Llewellyn Falco, Jason Jarrett Licensed under the Apache license.

版本与发布记录

@approval-tests/approvals 共发布 9 个版本,首次发布于 2026/09/26;过去 12 个月发布了 9 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
7.5.14latest2026/11/025 天前
7.5.132026/10/2216 天前
7.5.122026/10/2216 天前
7.5.112026/10/2019 天前
7.5.102026/10/2019 天前
7.5.92026/10/1919 天前

关于 @approval-tests/approvals 的常见问题

@approval-tests/approvals 是什么?

Approval Tests Library - Capturing Human Intelligence

如何安装 @approval-tests/approvals?

在项目目录运行 npm install @approval-tests/approvals,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 approvals,可以用 npx approvals 直接运行。

@approval-tests/approvals 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@approval-tests/approvals 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@approval-tests/approvals 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 0.8.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@approval-tests/approvals 可以商用吗?

@approval-tests/approvals 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@approval-tests/approvals 的下载量有多少?

根据 npm 官方下载统计,@approval-tests/approvals 在 2026/10/07 – 2026/11/05 这 30 天内被下载 22,709 次,日均约 757 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@approval-tests/approvals 还在维护吗?

最新版本 7.5.14 发布于 2026/11/02(5 天前);至今共发布 9 个版本,其中过去 12 个月发布了 9 个;首次发布于 2026/09/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。