我能够使用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'


当前回答

用一个包裹。json脚本

在package.json中使用"scripts": {"test": "jest"}:

npm test -- foo/__tests__/bar.spec.js

直接使用jest-cli

Globally-installed:

jest foo/__tests__/bar.spec.js

本地安装:

./node_modules/.bin/jest foo/__tests__/bar.spec.js

使用——testPathPattern

testPathPattern选项具有将路径作为未命名的位置参数传递给jest-cli的等效效果。看到normalize.ts。

./node_modules/.bin/jest --testPathPattern foo/__tests__/bar.spec.js

测试两个或多个特定文件

文件名用逗号或空格分隔:

./node_modules/.bin/jest foo/__tests__/bar.spec.js,foo/__tests__/foo.spec.js
./node_modules/.bin/jest foo/__tests__/bar.spec.js foo/__tests__/foo.spec.js

多次传递——testPathPattern:

./node_modules/.bin/jest --testPathPattern foo/__tests__/bar.spec.js --testPathPattern foo/__tests__/foo.spec.js

其他回答

下面的命令对我有用。 NPX jest -i file-name

不需要指定文件的完整路径,文件名就足够了。

编辑: 找到了另一种方法。 function -i file-name用于功能测试 运行test:integration -i file-name for integration test

也可以通过以下方法实现:

jest --findRelatedTests path/to/fileA.js

参考(Jest CLI选项)

如何在Nx monorepo中实现呢?下面是答案(在目录/path/to/workspace中):

npx nx test api --findRelatedTests=apps/api/src/app/mytest.spec.ts

参考和更多信息:如何在nx# 6中测试单个Jest测试文件

对于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"
  }
}

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

如果你不想全局安装笑话,你可以使用

npx jest foo.test.js