运行 测试来自 package.json 的文件夹中的文件夹

Running tests on folders within folders from package.json

我有一个应用 test 命令设置如下 package.json:

"test": "mocha --require babel-core/register --watch-extensions js **/*.test.js",

不幸的是,我的应用程序文件夹结构比该命令允许的要深。它看起来像这样:

app
└── someFolder
    └── subFolder
        └── subSubFolder
            └── fileNeedsToBeTest.js
            └── fileNeedsToBeTest.test.js
└── anotherFolder
    └── anotherFileNeedsToBeTest.js
    └── anotherFileNeedsToBeTest.test.js

问题是 test 命令的问题 我只能测试 anotherFolder 中的内容,但我还需要测试 someFolder/subFolder/subSubFolder 中的文件。我不想指定确切的路径,因为我在应用程序中有多个这样的实例。

如何修复我的 test 命令,以便能够找到 *.test.js 文件,无论它们在文件夹中有多深?

你的 glob 模式 **/*.test.js 应该用双引号引起来 ("..."),但是,因为它是在 JSON 中指定的,所以它们需要用反斜杠转义,即\"...\".

您的 test 命令应更改为以下内容:

"test": "mocha --require babel-core/register --watch-extensions js \"**/*.test.js\"",

这将在项目目录的根目录中找到所有以 .test.js 结尾的文件。

提示: 我假设您 app 文件夹存在于项目的根目录中,与 package.json 处于同一级别和 node_modules 目录。如果是这种情况,那么 glob 模式 **/*.test.js 可能会从 node_modules 目录中找到任何以 .test.js 结尾的文件——这将导致这些测试也是 运行。为防止出现这种情况,您可以取消 glob 模式中的 node_modules 目录,如下所示:

"test": "mocha --require babel-core/register --watch-extensions js \"{,!(node_modules)/**/}*.test.js\""

编辑:

回应以下评论:

...where does {,!(node_modules)/**/}*.test.js part of the command come from? What syntax is that?

Mocha utilizes node-glob as one of it's dependencies。该命令部分的语法由 node-glob 定义(...类似于 Bash 用于 globbing/pathname 扩展的语法)。

可以在 node-glob 文档的 Glob Primer 部分找到此语法的参考。

用于此场景的特定模式说明:

让我们分解该模式的相关部分...

             (A) Braced section
              │
    ┌─────────┴──────────┐
    {,!(node_modules)/**/}*.test.js
     │└──────┬──────┘└─┬┘ │└───┬───┘
     │       │         │  │    │
     │       │         │  │   (F) filename extension
     │       │         │  │
     │       │         │ (E) Single Globstar
     │       │         │
     │       │        (D) Double Globstar
     │       │
     │      (C) Negation section
     │
    (B) Comma-delimited
  • (A) 支撑部分: 文档将其描述为:

    Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with { and end with }, with any number of comma-delimited sections within. Braced sections may contain slash characters, so a{/b/c,bcd} would expand into a/b/c and abcd.

  • (B) 逗号分隔

    大括号部分以逗号分隔符开头,因为下一个否定部分,(以!开头的部分), 必须在另一个模式之后 - 它不能在开头。这里没有提供逗号分隔符之前的初始模式;在这种情况下,它仅表示项目目录(或者更具体地说,可能是存储 package.json 的 same/current 目录)。我们实际上可以将模式更改为以下任一模式,我们会得到相同的结果。

    {/,!(node_modules)/**/}*.test.js
     ^
    
    {./,!(node_modules)/**/}*.test.js
     ^^
    

    请注意,在逗号分隔符之前分别添加了 /./。这与我们可能定义资产路径的方式相同html、javascript等

  • (C)取反部分

    !表示"don't match this""ignore this"。文档将其描述为:

    !(pattern|pattern|pattern) Matches anything that does not match any of the patterns provided.

    在我们的场景中,它用于忽略 node_modules 文件夹。

  • (D) 双球星

    /**/ 部分匹配任意数量的字符,包括 /。也许更简单地说,它意味着扫描所有文件和子文件夹,无论有多深。

  • (E) 单星

    匹配文件名的所有字符 if/when 它们以提供的文件扩展名 (F) 结尾。

  • (F) 文件扩展名

    匹配所有以 .test.js 文件扩展名结尾的文件。