# @bahmutov/cy-grep 中文文档

规范地址：https://npmcn.com/package/%40bahmutov/cy-grep/

版本：3\.0\.5
npm 元数据更新时间：2026-09-08T13:38:32.065Z
中文译文更新时间：2026-11-07T14:59:30.533Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40bahmutov/cy-grep
原文对照：https://npmcn.com/package/%40bahmutov/cy-grep/?lang=original
项目主页：https://github.com/bahmutov/cy-grep
源码仓库：https://github.com/bahmutov/cy-grep

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：62.5 kB，8 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：6 个
- peer 依赖：cypress \>=8
- 首次发布：2022-12-15T03:00:44.906Z
- 最新版本发布：2026-09-08T13:38:31.684Z
- 近 30 天下载量：240223（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：89（近 12 个月 6 个）

## 中文简介

使用标题或标签过滤 Cypress 测试

## 安装

```sh
npm install @bahmutov/cy-grep
```

也可以使用：`pnpm add @bahmutov/cy-grep`、`yarn add @bahmutov/cy-grep`、`bun add @bahmutov/cy-grep`

## README

# @bahmutov/cy-grep (英语) ![cypress version](https://img.shields.io/badge/cypress-15.18.1-brightgreen)

> 使用子字符串或标签进行过滤测试

```shell
# run only tests with "hello" in their names
npx cypress run --expose grep=hello

  ✓ hello world
  - works
  - works 2 @tag1
  - works 2 @tag1 @tag2

  1 passing (38ms)
  3 pending
```

所有其他测试将标出待定,请查看为什么在 [Cypress 测试状态](https://on.cypress.io/writing-and-organizing-tests#Test-statuses) 博客文章.

如果您有多个 spec 文件,所有 specs 都会被加载,并且每个测试都会以同样的方式被过滤出,因为 grep 是运行时间操作,不能不加载就去除 spec 文件. 如果您想要只运行特定测试, 请使用内置 [\-- spec](https://on.cypress.io/command-line#cypress-run-spec-lt-spec-gt) CLI论点.

## 培训

看着视频 [输入到 cypress- grep 插件](https://www.youtube.com/watch?v=HS-Px-Sghd8) 学习我的Cypress课程 [线性插件](https://cypress.tips/courses/cypress-plugins)数字 :

-   [课程 k1: 设置测试 grep 插件](https://cypress.tips/courses/cypress-plugins/lessons/k1)
-   [课程 k2: 使用测试和套件标记过滤测试](https://cypress.tips/courses/cypress-plugins/lessons/k2)
-   [课程 k3: 过滤没有我们想要运行的标签的规格](https://cypress.tips/courses/cypress-plugins/lessons/k3)
-   [课程 k4: 过滤测试以使用多个标记运行](https://cypress.tips/courses/cypress-plugins/lessons/k4)
-   [课程 k5: 过滤测试以使用多个标记的 OR 运行](https://cypress.tips/courses/cypress-plugins/lessons/k5)
-   [课程 k6: 重复选中的测试 N 次](https://cypress.tips/courses/cypress-plugins/lessons/k6)
-   [课程 k7: 选择在交互模式下运行的测试](https://cypress.tips/courses/cypress-plugins/lessons/k7)
-   [课程 k8: 自动添加“ @” 字符的前缀标记](https://cypress.tips/courses/cypress-plugins/lessons/k8)
-   [课程 k9: 依据测试标记设置基准 Url](https://cypress.tips/courses/cypress-plugins/lessons/k9)
-   [课程 k10: 将测试标记限定为特定值](https://cypress.tips/courses/cypress-plugins/lessons/k10)
-   [课程 k11: 测试标记使用类型脚本 enum](https://cypress.tips/courses/cypress-plugins/lessons/k11)
-   [课程 k12: 验证用户提供的测试标签](https://cypress.tips/courses/cypress-plugins/lessons/k12)

将此插件与 [分压](https://github.com/bahmutov/cypress-split) 插件到第一个预过滤字符, 然后平行运行: 课 [C2: 组合分拆和分拆](https://cypress.tips/courses/cypress-split/lessons/c2) 从我的课程 [剪贴板插件](https://cypress.tips/courses/cypress-split)。 。 。 .

## 目录

-   [@bahmutov/cy-grep (英语)](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-bahmutovcy-grep-)
    -   [培训](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-training)
    -   [目录](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-table-of-contents)
    -   [安装](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-install)
        -   [支持文件](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-support-file)
        -   [配置文件](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-config-file)
        -   [10 前安装 Cypress 版本](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-install-in-cypress-versions-before-10)
    -   [使用概况](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-usage-overview)
    -   [通过测试标题过滤](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-filter-by-test-title)
        -   [或子字符串匹配](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-or-substring-matching)
        -   [测试套件](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-test-suites)
        -   [倒转过滤器](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-invert-filter)
    -   [带有标签的过滤器](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-filter-with-tags)
        -   [测试配置对象中的标记](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-tags-in-the-test-config-object)
        -   [标签](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-and-tags)
        -   [OR 标记](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-or-tags)
        -   [倒转标记](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-inverted-tags)
        -   [不标记](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-not-tags)
        -   [测试套件中的标记](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-tags-in-test-suites)
        -   [Grep 未标记测试](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-grep-untagged-tests)
        -   [访问测试中的标记](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-access-the-tags-in-the-test)
    -   [过滤前规格( grepFilterSpecs)](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-pre-filter-specs-grepfilterspecs)
    -   [Omit 过滤测试( grepOmitFiltered)](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-omit-filtered-tests-grepomitfiltered)
    -   [禁用 grep](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-disable-grep)
    -   [燃烧( 重复) 测试](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-burn-repeat-tests)
    -   [grepExtra 应用程序](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-grepextraspecs)
    -   [需要的标签](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-required-tags)
    -   [负重](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-negative-grep)
    -   [类型脚本支持](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-typescript-support)
    -   [grep 前缀](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-grepprefixat)
    -   [grepSpec 读取程序](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-grepspec)
    -   [一般咨询](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-general-advice)
    -   [DevTools 控制台](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-devtools-console)
        -   [grep 失败](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-grepfailed)
    -   [调试](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-debugging)
        -   [日志消息](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-log-messages)
        -   [在插件中调试](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-debugging-in-the-plugin)
        -   [在浏览器中调试](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-debugging-in-the-browser)
    -   [实例](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-examples)
    -   [另见](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-see-also)
    -   [cy-grep vs cypress-grep vs @ cypress/grep](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-cy-grep-vs-cypress-grep-vs-cypressgrep)
    -   [主要移徙](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-major-migrations)
        -   [v1 为 v2](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-v1-to-v2)
    -   [小型打印](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-small-print)

## 安装

假设您已安装 Cypress, 请添加此模块为 dev 依赖 .

```shell
# using NPM
npm i -D @bahmutov/cy-grep
# using Yarn
yarn add -D @bahmutov/cy-grep
```

**说明**@bahmutov/cy-grep应该与所有Cypress版本合作.

### 支持文件

**要求:** 从中装入此模块 [支持文件](https://on.cypress.io/writing-and-organizing-tests#Support-file) 如果没有使用支持文件,则在 spec 文件上方。 您导入注册函数, 然后调用 :

```js
// cypress/support/e2e.js

// load and register the grep feature using "require" function
// https://github.com/bahmutov/cy-grep
const registerCypressGrep = require('@bahmutov/cy-grep')
registerCypressGrep()

// if you want to use the "import" keyword
// note: `./index.d.ts` currently extends the global Cypress types and
// does not define `registerCypressGrep` so the import path is directly
// pointed to the support file
import registerCypressGrep from '@bahmutov/cy-grep/src/support'
registerCypressGrep()

// "import" with `@ts-ignore`
// @see error 2306 https://github.com/microsoft/TypeScript/blob/3fcd1b51a1e6b16d007b368229af03455c7d5794/src/compiler/diagnosticMessages.json#L1635
// @ts-ignore
import registerCypressGrep from '@bahmutov/cy-grep'
registerCypressGrep()
```

### 配置文件

**选项:** 从中装入并注册此模块 [配置文件](https://docs.cypress.io/guides/references/configuration#setupNodeEvents)数字 :

```js
// cypress.config.js
{
  e2e: {
    setupNodeEvents(on, config) {
      require('@bahmutov/cy-grep/src/plugin')(config);
      // IMPORTANT: return the config object
      return config;
    },
  }
}
```

通过安装插件 `setupNodeEvents()` 实现 [grepFilter 服务器](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-pre-filter-specs-grepfilterspecs) 特性.

**提示 :** 您可能想要设置这些 `expose` 配置文件中的设置

```js
module.exports = defineConfig({
  expose: { grepFilterSpecs: true, grepOmitFiltered: true },
  ...
})
```

试图调用插件功能而无需任何参数或不止一个参数会丢出一个错误

```js
// ERROR: forgot the config file
setupNodeEvents(on, config) {
  require('@bahmutov/cy-grep/src/plugin')();
}
// ERROR: too many arguments
setupNodeEvents(on, config) {
  require('@bahmutov/cy-grep/src/plugin')(on, config);
}
```

### 10 前安装 Cypress 版本

见 [测试-cy-v9](https://npmcn.com/package/%40bahmutov/cy-grep/test-cy-v9/) 比如说

```js
// cypress/plugins/index.js
module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
  require('@bahmutov/cy-grep/src/plugin')(config)
  // IMPORTANT: return the config object
  return config
}
```

```js
// cypress/support/index.js
require('@bahmutov/cy-grep')()
```

将常见设置放入 `cypress.json`

```json
{
  "expose": {
    "grepOmitFiltered": true,
    "grepFilterSpecs": true
  }
}
```

## 使用概况

您可以通过过滤测试来使用其标题的一部分运行 `grep`,并通过明确的标记通过 `grepTags` Cypress环境变量.

您很可能从命令行中通过这些环境变量 。 例如,只运行标题有"login"并被标记为"smoke"的测试,您会运行:

以下是几个例子:

```shell
# run only the tests with "auth user" in the title
$ npx cypress run --expose grep="auth user"
# run tests with "hello" or "auth user" in their titles
# by separating them with ";" character
$ npx cypress run --expose grep="hello; auth user"
# run tests tagged @fast
$ npx cypress run --expose grepTags=@fast
# run only the tests tagged "smoke"
# that have "login" in their titles
$ npx cypress run --expose grep=login,grepTags=smoke
# only run the specs that have any tests with "user" in their titles
$ npx cypress run --expose grep=user,grepFilterSpecs=true
# only run the specs that have any tests tagged "@smoke"
$ npx cypress run --expose grepTags=@smoke,grepFilterSpecs=true
# run only tests that do not have any tags
# and are not inside suites that have any tags
$ npx cypress run --expose grepUntagged=true
```

您可以使用任何方式修改环境值 `grep` 财务报告和审定财务报表 `grepTags`,但运行时间除外 `Cypress.expose('grep')` (因为时间太晚) 你可以设置 `grep` 数值 `cypress.json` 仅用子字符串运行的文件 `viewport` 他们的名字

```json
{
  "expose": {
    "grep": "viewport"
  }
}
```

您也可以设置 `expose.grep` 对象在插件文件中,但记得返回已更改的配置对象:

```js
// cypress/plugin/index.js
module.exports = (on, config) => {
  config.expose.grep = 'viewport'
  return config
}
```

您也可以在交互模式下运行 Cypress 时设置 DevTools 控制台的 grep和 grepTags `cypress open`,参见 [DevTools 控制台部分](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-devtools-console)。 。 。 .

## 通过测试标题过滤

```shell
# run all tests with "hello" in their title
$ npx cypress run --expose grep=hello
# run all tests with "hello world" in their title
$ npx cypress run --expose grep="hello world"
```

### 或子字符串匹配

您可以通过多个标题子字符串来匹配它们与 `;` 字符键。 每个下弦被修剪.

```shell
# run all tests with "hello world" or "auth user" in their title
$ npx cypress run --expose grep="hello world; auth user"
```

### 测试套件

过滤器也应用于"描述"区块. 在这种情况下,如果它们的外出套房被启用,则进行检测.

```js
describe('block for config', () => {
  it('should run', () => {})

  it('should also work', () => {})
})
```

```
# run any tests in the blocks including "config"
--expose grep=config
```

**说明:** 全球职能 `describe` 财务报告和审定财务报表 `context` 是由此插件支持的别名.

### 倒转过滤器

```shell
# run all tests WITHOUT "hello world" in their title
$ npx cypress run --expose grep="-hello world"
# run tests with "hello", but without "world" in the titles
$ npx cypress run --expose grep="hello; -world"
```

## 带有标签的过滤器

您可以选择要运行的测试, 或者通过通过标记跳过 `--expose grepTags=...` 数值.

```
# enable the tests with tag "one" or "two"
--expose grepTags="one two"
# enable the tests with both tags "one" and "two"
--expose grepTags="one+two"
# enable the tests with "hello" in the title and tag "smoke"
--expose grep=hello,grepTags=smoke
```

如果您可以在环境变量中通过逗号 `grepTags`,您可以使用 `,` 以分隔标签

```
# enable the tests with tag "one" or "two"
CYPRESS_grepTags=one,two npx cypress run
```

如果在规格中找不到特定的标记, 您将在终端中收到警告 :

```
$ npx cypress run --expose grepTags=@wrong-tag
cy-grep: could not find the tag "@wrong-tag" in any of the specs
```

### 测试配置对象中的标记

Cypress测试可以有自己的 [测试配置对象](https://on.cypress.io/configuration#Test-Configuration),在使用此插件时,您可以将测试标记放在那里,或者作为单一标记字符串,或者作为标记的数组.

```js
it('works as an array', { tags: ['config', 'some-other-tag'] }, () => {
  expect(true).to.be.true
})

it('works as a string', { tags: 'config' }, () => {
  expect(true).to.be.true
})
```

你可以使用两种测试 `--expose grepTags=config` 绳子.

### 标签

使用 `+` 要求两个标签都存在

```
--expose grepTags=@smoke+@fast
```

### OR 标记

您可以使用空格运行匹配此标签的测试 。 确保引用grep字符串!

```
# run tests with tags "@slow" or "@critical" in their names
--expose grepTags='@slow @critical'
```

### 倒转标记

您可以使用倒置选项使用特定标记跳过测试: 标记前加字符 `-`。 。 。 .

```
# do not run any tests with tag "@slow"
--expose grepTags=-@slow
```

如果您想要用标签运行所有测试 `@slow` 但没有标签 `@smoke`数字 :

```
--expose grepTags=@slow+-@smoke
```

**说明:** 倒转标签过滤器不兼容 `grepFilterSpecs` 选项

### 不标记

您可以使用特定标记跳过运行测试, 即使它们有一个应该运行的标记, 使用非选项: 标记的前缀为 `--`。 。 。 .

注意这和附件相同 `+-<tag to never run>` 每个标签。 用大量的标记可能有用.

如果你想用标签进行测试 `@slow` 或者说 `@regression` 但没有标签 `@smoke`

```
--expose grepTags='@slow @regression --@smoke'
```

等值为

```
--expose grepTags='@slow+-@smoke @regression+-@smoke'
```

### 测试套件中的标记

标记也应用于"说明"块. 在这种情况下,如果它们的外出套房被启用,则进行检测.

```js
describe('block with config tag', { tags: '@smoke' }, () => {})
```

```
# run any tests in the blocks having "@smoke" tag
--expose grepTags=@smoke
# skip any blocks with "@smoke" tag
--expose grepTags=-@smoke
```

见 [cypress/整合/描述-tags-spec.js](https://npmcn.com/package/%40bahmutov/cy-grep/cypress/integration/describe-tags-spec.js) 文档.

**说明:** 全球职能 `describe` 财务报告和审定财务报表 `context` 是由此插件支持的别名.

### Grep 未标记测试

有时你想在没有任何标记的情况下只进行测试,这些测试在描述块内没有任何标记.

```
$ npx cypress run --expose grepUntagged=true
```

### 访问测试中的标记

您可以检查当前测试的标记( 包括其父套件) `Cypress.expose('testTags')` 列表

```js
describe('parent', { tags: ['@p1', '@p2'] }, () => {
  describe('child', { tags: '@c1' }, () => {
    it('has all effective test tags', { tags: '@t1' }, () => {
      const tags = Cypress.expose('testTags')
      // includes tags from the parent suites and the test itself
      expect(tags, 'tags').to.deep.equal(['@p1', '@p2', '@c1', '@t1'])
    })
  })
})
```

此外,您还可以检查当前光谱内每次测试的标签和所需的标签 `Cypress.expose('specTags')` 对象

见 [谱.js](https://npmcn.com/package/%40bahmutov/cy-grep/cypress/e2e/spec.js) 用于实际测试实例.

示例输出 :

```js
{
    "hello world": {
        "effectiveTestTags": [],
        "requiredTestTags": []
    },
    "works": {
        "effectiveTestTags": [],
        "requiredTestTags": []
    },
    "works 2 @tag1": {
        "effectiveTestTags": [
            "@tag1"
        ],
        "requiredTestTags": []
    },
    "works 2 @tag1 @tag2": {
        "effectiveTestTags": [
            "@tag1",
            "@tag2"
        ],
        "requiredTestTags": []
    },
    "works @tag2": {
        "effectiveTestTags": [
            "@tag2"
        ],
        "requiredTestTags": []
    }
}
```

## 过滤前规格( grepFilterSpecs)

默认使用时 `grep` 财务报告和审定财务报表 `grepTags` 执行所有规格,并在每个过滤器内应用。 如果只包含几个细节,那就太浪费了 `grep` 在测试标题中。 因此,当做积极的 `grep`您可以使用 `grepFilterSpecs=true` 参数.

```shell
# filter all specs first, and only run the ones with
# suite or test titles containing the string "it loads"
$ npx cypress run --expose grep="it loads",grepFilterSpecs=true
# filter all specs files, only run the specs with a tag "@smoke"
$ npx cypress run --expose grepTags=@smoke,grepFilterSpecs=true
```

**说明1:** 这需要在您的工程的插件文件中安装此插件, 请参见 [安装](https://npmcn.com/package/%40bahmutov/cy-grep/#readme-install)。 。 。 .

**说明2:** 页:1 `grepFilterSpecs` 选项只与正数兼容 `grep` 财务报告和审定财务报表 `grepTags` 选项,而不是负(倒转)“-...”过滤器.

**说明3:** 如果过滤后没有剩余文件,插件会打印出一个警告并保留所有文件不变,以避免测试跑取器在“没有找到规格”时出错.

**提示 :** 您可以在 [配置文件](https://docs.cypress.io/guides/references/configuration) 文件以默认方式启用并跳过环境变量 :

```js
// config file
{
  "e2e": {
    "env": {
      "grepFilterSpecs": true
    }
  }
}
```

## Omit 过滤测试( grepOmitFiltered)

默认情况下, 所有过滤测试都会进行 _待处理_ 使用 `it.skip` 方法。 如果你想完全省略,请通过环境变量 `grepOmitFiltered=true`。 。 。 .

有待过滤的测试

```
cypress run --expose grep="works 2"
```

![Pending tests](https://npmcn.com/package/%40bahmutov/cy-grep/images/includes-pending.png)

Omit 过滤测试

```
cypress run --expose grep="works 2",grepOmitFiltered=true
```

![Only running tests remaining](https://npmcn.com/package/%40bahmutov/cy-grep/images/omit-pending.png)

**提示 :** 您可以在配置文件中设置此环境变量( 通常是) `cypress.config.js`默认启用它的文件,并使用环境变量跳过:

```json
{
  "env": {
    "grepOmitFiltered": true
  }
}
```

## 禁用 grep

如果您指定 `grep` 参数 [配置文件](https://docs.cypress.io/guides/references/configuration),您可以从命令行中禁用它

```
$ npx cypress run --expose grep=,grepTags=,burn=
```

## 燃烧( 重复) 测试

你可以烧掉过滤过的测试以确保它们无片状

```
npx cypress run --expose grep="hello world",burn=5
```

您可以通过环境名称传递测试的次数 `burn` 或者说 `grepBurn` 或者说 `grep-burn`注意,如果很多测试都符合grep和grep标签,很多测试会被烧掉!

如果不指定“ grep” 或“ grep 标记” 选项, “ burn” 将重复 _每个_ 测试.

## grepExtra 应用程序

有时您想要使用标记进行预过滤的规格,然后在没有过滤的情况下运行额外的规格. 您可以使用 `grepExtraSpecs` env 字符串。 例如,使用标签过滤规格 `@a` 并运行"b.cy.js":

```
npx cypress run --expose grepTags=@a,grepExtraSpecs=cypress/e2e/b.cy.js
```

## 需要的标签

有时候你可能会想做一个测试 或者一套测试 _仅限_ 如果存在特定的标记或标记。 例如,你可能会有一个测试来清理数据. 这个测试是为了夜跑,而不是每次测试运行. 这样你就可以设置一个 `required` 标签 :

```js
it('cleans up the data', { requiredTags: '@nightly' }, () => {...})
```

当你现在运行测试, 这个测试会跳过, 仿佛它是 `it.skip`。它只有在使用标记时才会运行 `@nightly`,例如: `npx cypress run --expose grepTags=@nightly`。 。 。 .

若为 `grepFilterSpecs=true` 而一个 spec 仅需要标记,而您正在运行中没有任何标记,此 spec 将被完全跳过 .

校对:Soup [需要的标记](https://glebbahmutov.com/blog/required-tags/) 财务报告和审定财务报表 [使用必要的测试标记而不是跳过测试](https://glebbahmutov.com/blog/required-tags-instead-of-skipped-tests/)。 。 。 .

## 负重

在按标题进行重写测试时,包含母套件标题. 例如如果这是光谱

```js
describe('users', () => {
  it('works 1', () => {})
  it('works 2', () => {})
  it('works 3', () => {})
})

describe('projects', () => {
  it('load 1', () => {})
  it('load 2', () => {})
  it('load 3', () => {})
})
```

您可以使用 `--expose grep=projects` 你可以跳过测试 在套房 `projects` 通过使用 `--expose grep=-projects`。 。 。 .

## 类型脚本支持

因为 Cypress 测试配置对象类型定义没有 `tags` 我们在上面使用的属性, TypeScript linter 将显示一个错误。 在测试上添加一个忽略的注释:

```js
// @ts-ignore
it('runs on deploy', { tags: 'smoke' }, () => {
  ...
})
```

如果您想要允许任何字符串成为测试标记, 请简单包含 [src/tags - 是- strings.d.ts (中文(简体) )](https://npmcn.com/package/%40bahmutov/cy-grep/src/tags-are-strings.d.ts) 在您的项目 TS 配置中包含此软件包 :

```json
{
  "include": [
    "cypress/**/*",
    "node_modules/@bahmutov/cy-grep/src/tags-are-strings.d.ts"
  ],
  "compilerOptions": {
    "types": ["cypress", "@bahmutov/cy-grep"]
  }
}
```

如果你想提供你的 _拥有_ 标签列表,创建 `.d.ts` 文件或扩展名 `index.d.ts` 文件

```ts
// your project's index.d.ts file
/// <reference types="cypress" />

/**
 * The only allowed test tags in this project
 */
type AllowedTag = '@smoke' | '@misc' | '@new-todo'

declare namespace Cypress {
  interface SuiteConfigOverrides {
    tags?: AllowedTag | AllowedTag[]
    requiredTags?: AllowedTag | AllowedTag[]
  }

  interface TestConfigOverrides {
    tags?: AllowedTag | AllowedTag[]
    requiredTags?: AllowedTag | AllowedTag[]
  }
}
```

## grep 前缀

使用开始的测试标记 `@` 如此常见, 您可以使用 env 选项执行 `grepPrefixAt: true`。允许您使用 `@tag1,@tag2, ...` 或者说 `tag1,tag2, ...` 打电话的时候.

```
# use grepPrefixAt in your env settings object
# use { tags: '@tag1' } in your tests

# then these two are equivalent
--expose grepTags=@tag1
--expose grepTags=tag1
```

## grepSpec 读取程序

如果用户选择要运行的 spec (s) , 那么它可能会与 `grepFilterSpecs=true` 用来过滤光谱。 如果用户使用, 无法“ 知道 ” `--spec <...>` 选项 [33个](https://github.com/bahmutov/cy-grep/issues/33) 财务报告和审定财务报表 [26032号](https://github.com/cypress-io/cypress/issues/26032)因此,如果你使用 `--spec pattern`,您需要通过 `CYPRESS_grepSpec=pattern` 或者说 `--expose grepSpec=pattern` 选项.

```
cypress run --spec a.cy.js --expose grepTags=...,grepSpec=a.cy.js
```

## 一般咨询

-   很简单.
-   我喜欢用 `@` 作为标签前缀, 使标签可以搜索

```js
// ✅ good practice
describe('auth', { tags: '@critical' }, () => ...)
it('works', { tags: '@smoke' }, () => ...)
it('works quickly', { tags: ['@smoke', '@fast'] }, () => ...)

// 🚨 NOT GOING TO WORK
// ERROR: treated as a single tag,
// probably want an array instead
it('works', { tags: '@smoke @fast' }, () => ...)
```

窃取测试

```shell
# run the tests by title
$ npx cypress run --expose grep="works quickly"
# run all tests tagged @smoke
$ npx cypress run --expose grepTags=@smoke
# run all tests except tagged @smoke
$ npx cypress run --expose grepTags=-@smoke
# run all tests that have tag @fast but do not have tag @smoke
$ npx cypress run --expose grepTags=@fast+-@smoke
```

我会进行所有的测试 默认, 和grep测试 从命令行。 例如,我可以先使用grep插件进行烟雾测试,如果烟雾测试通过,然后进行所有测试. 看视频 [我如何组织拉动请求工作流程 首先进行烟雾测试](https://www.youtube.com/watch?v=SFW7Ecj5TNE) 联 合 国 [拖动请求工作流程文件](https://github.com/bahmutov/cypress-grep-example/blob/main/.github/workflows/pr.yml)。 。 。 .

## DevTools 控制台

您可以从 DevTools 控制台设置 grep 字符串 。 此插件添加方法 `Cypress.grep` 财务报告和审定财务报表 `Cypress.grepTags` 设置 grep 字符串并重新启动测试

```js
// filter tests by title substring
Cypress.grep('hello world')
// run filtered tests 100 times
Cypress.grep('hello world', null, 100)
// filter tests by tag string
// in this case will run tests with tag @smoke OR @fast
Cypress.grep(null, '@smoke @fast')
// run tests tagged @smoke AND @fast
Cypress.grep(null, '@smoke+@fast')
// run tests with title containing "hello" and tag @smoke
Cypress.grep('hello', '@smoke')
// run tests with title containing "hello" and tag @smoke 10 times
Cypress.grep('hello', '@smoke', 10)
```

-   删除 grep 字符串输入 `Cypress.grep()`

### grep 失败

测试完成后,你可以从 DevTools 控制台运行失败的测试

```text
> Cypress.grepFailed()
```

**提示 :** 使用情况 `Cypress.grep()` 重设和运行所有测试

校对:Soup [运行 Cypress 中的失败测试](https://glebbahmutov.com/blog/run-failed-tests/)。 。 。 .

## 调试

调试一个问题时, 首先确定您正在使用此插件的预期版本, 因为一些特性可能只在 [以后的释放](https://github.com/bahmutov/cy-grep/releases)。 。 。 .

```
# get the plugin's version using NPM
$ npm ls @bahmutov/cy-grep
...
└── @bahmutov/cy-grep@1.1.0

# get the plugin's version using Yarn
$ yarn why @bahmutov/cy-grep
...
=> Found "@bahmutov/cy-grep@1.1.0"
info Has been hoisted to "@bahmutov/cy-grep"
info This module exists because it's specified in "devDependencies".
...
```

第二,检查 Cypress 桌面 GUI 屏幕中的“ 设置” 标签, 以确保将数值正确传递到插件 。 您应该看到您在“ 定义” 对象下所传递的值 `env` 属性。 例如,如果我以

```text
$ npx cypress open --expose grep=works,grepFilterTests=true
```

然后,我期待看到grep字符串 和"过滤测试"旗帜 `env` 对象.

![Values in the env object](https://npmcn.com/package/%40bahmutov/cy-grep/images/config.png)

### 日志消息

此模块使用 [调试](https://github.com/visionmedia/debug#readme) 以记录动词消息。 您可以启用插件文件中的调试消息( 当发现要过滤的光谱时运行), 并在浏览器内部查看它如何决定要运行和跳过哪些测试 。 在打开新一期时,请提供插件(如果有的话)和浏览器的调试日志.

### 在插件中调试

用环境变量启动 Cypress `DEBUG=cy-grep`。您将在终端输出中看到此插件的一些消息 :

```
$ DEBUG=cy-grep npx cypress run --expose grep=works,grepFilterSpecs=true
cy-grep: tests with "works" in their names
cy-grep: filtering specs using "works" in the test title
  cy-grep Cypress config env object: { grep: 'works', grepFilterSpecs: true }
  ...
  cy-grep found 1 spec files +5ms
  cy-grep [ 'spec.js' ] +0ms
  cy-grep spec file spec.js +5ms
  cy-grep suite and test names: [ 'hello world', 'works', 'works 2 @tag1',
    'works 2 @tag1 @tag2', 'works @tag2' ] +0ms
  cy-grep found "works" in 1 specs +0ms
  cy-grep [ 'spec.js' ] +0ms
```

### 在浏览器中调试

要启用浏览器中的调试控制台消息, 请从 DevTools 控制台设置中 `localStorage.debug='cy-grep'` 并再次进行测试.

要查看如何调试此插件, 请观看视频 [调试cypress-grep 插件](https://youtu.be/4YMAERddHYA) 但使用字符串 `cy-grep`

## 实例

-   [cypress-grep-实例](https://github.com/bahmutov/cypress-grep-example)
-   [todo-graphql-实例](https://github.com/bahmutov/todo-graphql-example)

## 另见

-   [cypress - select - tests (简体中文)](https://github.com/bahmutov/cypress-select-tests)
-   [cypress-skip 测试](https://github.com/cypress-io/cypress-skip-test)
-   校对:Soup [Cypress GitHub 动作斜线命令](https://glebbahmutov.com/blog/cypress-slash-command/)
-   校对:Soup [类型检查您的测试标记](https://glebbahmutov.com/blog/type-check-test-tags/)
-   插件 [dennisbergevin/cypress-plugin-最后失败](https://github.com/dennisbergevin/cypress-plugin-last-failed)
-   插件 [dennisbergevin/ cypress- cli- 选择](https://github.com/dennisbergevin/cypress-cli-select)
-   插件 [dennisbergevin/cypress-plugin-grep-boxes 黑匣子 黑匣子](https://github.com/dennisbergevin/cypress-plugin-grep-boxes)

## cy-grep vs cypress-grep vs @ cypress/grep

多年前我写了一个插件 `cypress-grep`当我离开Cypress公司时, 我把麻省理工学院的牌照插件转给了Cypress GitHub组织。 他们把它移动到 Cypress monorepo 并更名为国家预防机制模块 `@cypress/grep`。我在一些工程中仍然使用这个grep插件。 当Cypress v10发布时,它打破了插件中的一些东西. 由于我需要快速修复它 和单相机的设置是次优的, 我将插件重新推回我自己的回相机 `bahmutov/cy-grep` 以国家预防机制的名义发布 `@bahmutov/cy-grep`。 。 。 .

我打算维护插件 `@bahmutov/cy-grep` 将来,因为我靠自己 **经常**。 。 。 .

## 主要移徙

### v1 为 v2

添加类型 `tags` 财务报告和审定财务报表 `requiredTags` 从默认移到自己的 `.d.ts` 文档.

**单曲**

例如,插件 `@bahmutov/cy-grep@v1` 只是可以增加自己在 `types` 列表中 `tsconfig.json` 编号 : `jsconfig.json` 文件

```json
{
  "include": ["cypress/**/*"],
  "compilerOptions": {
    "types": ["cypress", "@bahmutov/cy-grep"]
  }
}
```

这让 `tags` 属性字符串,所以您可以使用 `it('works', { tags: '@smoke' }, () => ...)`

**页:1**

如果你想使用的话 _任意_ 作为标签的字符串, 您需要添加文件 [src/tags - 是- strings.d.ts (中文(简体) )](https://npmcn.com/package/%40bahmutov/cy-grep/src/tags-are-strings.d.ts)

```json
{
  "include": [
    "cypress/**/*",
    "node_modules/@bahmutov/cy-grep/src/tags-are-strings.d.ts"
  ],
  "compilerOptions": {
    "types": ["cypress", "@bahmutov/cy-grep"]
  }
}
```

**说明:** 您仍然想要包含 `@bahmutov/cy-grep` 默认类型,因为它们提供了额外的静态方法,例如 `Cypress.grep`

## 小型打印

作者: Gleb Bahmutov <gleb.bahmutov@gmail.com > 2022年

-   [@bahmutov (英语)](https://twitter.com/bahmutov)
-   [glebbahmutov.com (中文(简体) )](https://glebbahmutov.com/)
-   [博客](https://glebbahmutov.com/blog)
-   [视频](https://www.youtube.com/glebbahmutov)
-   [专题介绍](https://slides.com/bahmutov)
-   [cypress.tips (英语)](https://cypress.tips/)
-   [Cypress Tips & Tricks 通讯](https://cypresstips.substack.com/)
-   [我的Cypress课程](https://cypress.tips/courses)

许可:麻省理工学院 - 做任何与代码有关的事情, 但如果它不起作用,不要责怪我.

支持: 如果您发现此模块有任何问题, 电子邮件 / 微博 / [未决问题](https://github.com/bahmutov/cy-grep/issues) 在基图布

## 常见问题

### @bahmutov/cy-grep 是什么？

使用标题或标签过滤 Cypress 测试

### 如何安装 @bahmutov/cy-grep？

在项目目录运行 npm install @bahmutov/cy-grep，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：cypress（\>=8）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @bahmutov/cy-grep 支持 TypeScript 吗？

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

### @bahmutov/cy-grep 支持 ESM 还是 CommonJS？

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

### @bahmutov/cy-grep 可以商用吗？

@bahmutov/cy-grep 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @bahmutov/cy-grep 的下载量有多少？

根据 npm 官方下载统计，@bahmutov/cy-grep 在 2026/10/08 – 2026/11/06 这 30 天内被下载 240,223 次，日均约 8,007 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @bahmutov/cy-grep 还在维护吗？

最新版本 3\.0\.5 发布于 2026/09/08（1 个月前）；至今共发布 89 个版本，其中过去 12 个月发布了 6 个；首次发布于 2022/12/15。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

