我能够使用Jest测试多个文件,但我不知道如何测试单个文件。

我有:

执行npm install jest-cli——save-dev命令 更新包。Json: '{…"scripts": {"test": "jest"}…} 编写了许多测试。

运行npm测试可以正常工作(目前运行14个测试)。

如何测试单个文件,例如test app/foo/__tests__/bar.spec.js?

我已经尝试运行npm test app/foo/__tests__/bar.spec.js(从项目根),但我得到以下错误:

npm犯错!错误:ENOENT,打开'/node_modules/app/foo/tests/bar.spec.js/package.json'


当前回答

如果你正在运行npm >= 5.2.0,并且你已经在本地安装了一个带有npm i -d Jest的devDependencies,你可以通过执行npx Jest /path/to/your/spec.js在一个特定的文件上运行Jest。

其他回答

Jest将使用您传递的内容作为正则表达式模式。它会匹配。

如果您想运行一个特定的测试文件,那么最好的方法是使用它的精确完整路径。(你也可以指定一个特定的相对路径,比如(src/XFolder/index.spec.ts))。

在Linux中提供目录中完整路径的最简单方法是:

jest $PWD/index.spec.ts

注意变量$PWD的使用。

对于Windows !(待更新)

我只是将Jest安装为全局,运行Jest myFileToTest.spec.js,它工作了。

对于NestJS用户,简单的替代方法是使用,

npm test -t <name of the spec file to run>

NestJS预先配置了测试文件的正则表达式,以便在Jest的情况下搜索。

一个简单的例子是-

npm test -t app-util.spec.ts

(这是我的。spec文件名)

不需要给出完整的路径,因为Jest会根据NestJS默认可用的配置来搜索.spec文件:

"jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

使用该命令:

npx jest test --runTestsByPath <path-to-file>

运行单个测试:

npm test -t ValidationUtil # `ValidationUtil` is my module `ValidationUtil.spec.js`

-t -在后面,放置一个包含测试名称的正则表达式。