如何使用Jest测试单个文件?

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

我有:

  • 运行npm install jest-cli --save-dev
  • 已更新package.json:'{…"脚本":{"test":"jest"}…}
  • 笔试考试数量。

运行npm test按预期工作(目前运行14个测试)。

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

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

错误:ENOENT, open'/node_modules/app/foo/测试/bar.spec.js/package.json'

768813 次浏览

至少2019年:

npm test -- bar.spec.js

2015年:

为了运行特定的测试,您需要使用jest命令。npm test将不起作用。要直接在命令行上访问jest,请通过npm i -g jest-cliyarn global add jest-cli安装它。

然后只需使用jest bar.spec.js运行您的特定测试。

说明:您不必输入测试文件的完整路径。参数被解释为正则表达式。唯一标识文件的完整路径的任何部分都足够了。

你所要做的就是吟唱魔法咒语:

npm test -- SomeTestFileToRun

独立的--是标记选项结束的*nix魔法,这意味着(对于NPM)之后的所有内容都传递给正在运行的命令,在本例中为jest。顺便说一句,您可以通过以下方式显示Jest用法说明

npm test -- --help

总之,吟唱

npm test -- Foo

在命名文件(FooBar.js)中运行测试。不过,您应该注意:

  • Jest将名称视为区分大小写,因此如果您使用不区分大小写但保留大小写的文件系统(如WindowsNTFS),您可能会遇到看似奇怪的情况。

  • Jest似乎将规范视为前缀。

所以上面的咒语会

  • 运行FooBar.jsFoo.jsFooZilla.js
  • 但是没有运行foo.js

使用npm test并不意味着Jest是全局安装的。它只是意味着“测试”映射到在您的package.json文件中使用Jest。

在项目的根级别,以下工作:

npx jest [file or directory]

file or directory可以是您要运行的测试文件,也可以是包含多个文件的目录。

要运行单个测试:

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

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

如果您使用纱线,您可以直接在以下位置添加.spec.js.test.js文件:

yarn test src/lib/myfile.test.js

这是我的package.json文件中的部分,Jest安装为本地包(删除了相关部分):

{
...
"scripts": {
"test": "jest",
"testw": "jest --watch",
"testc": "jest --coverage",
...
},
"devDependencies": {
"jest": "^18.1.0",
...
},


}

如果您正在运行npm >= 5.2.0并且您已将Jest本地安装为devDependenciesnpm i -d jest,则可以通过执行npx jest /path/to/your/spec.js在特定文件上运行Jest。

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

这就是我在特定文件上动态运行测试而无需重新启动测试的方式。

我的React项目创建为create-react-app

因此,它会监视测试以进行更改,并在我进行更改时自动运行测试。

这是我在终端的测试结果末尾看到的:

Test Suites: 16 passed, 16 total
Tests:       98 passed, 98 total
Snapshots:   0 total
Time:        5.048s
Ran all test suites.


Watch Usage: Press w to show more.

W

Watch Usage
› Press f to run only failed tests.
› Press o to only run tests related to changed files.
› Press q to quit watch mode.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press Enter to trigger a test run.

然后按P

Pattern Mode Usage
› Press Esc to exit pattern mode.
› Press Enter to filter by a filenames regex pattern.


pattern ›


Start typing to filter by a filename regex pattern.


这是在我想在“登录”文件夹中运行“index.es6.js”文件之后:

Pattern Mode Usage
› Press Esc to exit pattern mode.
› Press Enter to filter by a filenames regex pattern.


pattern › login/index


Pattern matches 1 file
› src/containers/Login/index.es6.test.js

这就是我在特定文件上运行测试的方式。

你有两个选择:

  • 选项1:命令行。您可以运行以下命令

    node '/Users/complete-path-to-you-project/your-project/node_modules/.bin/jest' '/Users/complete-path-to-you-project/your-project/path-to-your-file-within-the-project/your-file.spec.ts'
    

    这避免了您全局安装Jest。您使用项目使用的jest。

  • 选项2:如果您使用的是Visual Studio代码,您有一个很棒的插件可以做到这一点:JestRunner。它不仅允许您逐个文件运行测试,甚至可以通过右键单击您要运行的测试来运行特定的套件和规范。

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

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

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

jest $PWD/index.spec.ts

注意变量$PWD的使用。

在此输入图片描述

适用于Windows!(待更新)

您可以将文件名与npm test --一起使用:

npm test -- fileName.jsx

还可以通过以下方式实现:

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测试文件

我们将nrwl-nxAngular一起使用。在这种情况下,我们可以使用此命令:

npm test <ng-project> -- --testFile "file-name-part"

备注:

  • npm test将运行package.json中指定的测试脚本: "test": "ng test"
  • --:告诉npm将以下参数传递给测试脚本(而不是消耗它们)
  • 因此,cmd的其余部分将被传递给ng test
    • <ng-project>angular.json中项目的名称
      • 当您省略此参数时,将使用"defaultProject"(在angular.json中指定)(因此当测试不在默认项目中时,您必须指定它)
    • 接下来我们必须检查使用了哪个构建器:
      • angular.json中导航到"project"-"<ng-project>"-"architect"-"test"
      • 并检查"builder",在我们的例子中是:"@nrwl/jest:jest"
    • 现在我们知道了构建器,我们需要找到可用的cmd行参数
      • 在命令行上,运行npm test <ng-project> -- --help以查看所有可用选项
      • 或查看在线留档
    • 其中一个选项是这里使用的--testFile

使用Angular和Jest,您可以将其添加到“脚本”下的文件package.json中:

"test:debug": "node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand"

然后运行一个单元测试为一个特定的文件您可以写这个命令在您的终端

npm run test:debug modules/myModule/someTest.spec.ts

不需要传递完整路径。只需使用正则表达式模式。

yarn jest --testNamePattern my_test_name
yarn jest -t=auth
yarn jest -t component # This will test all whose test name contains `component`


yarn jest --testPathPattern filename # This will match the file path
yarn jest filename # This will match the file path, the same with above
import LoggerService from '../LoggerService ';


describe('Method called****', () => {
it('00000000', () => {
const logEvent = jest.spyOn(LoggerService, 'logEvent');
expect(logEvent).toBeDefined();
});
});

用法:

npm test -- __tests__/LoggerService.test.ts -t '00000000'

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

测试用例":"ds_serverapi/ds_server.test.js"

Jest留档:

  "scripts": {
"test": "jest path/to/my-test.js"
}

运行这个与

 npm run test

当时我用的是:

yarn test TestFileName.spec.js

你不应该输入完整的路径。这对我在Windows 10机器上有效。

如果您安装Visual Studio Code插件JestRunner

在此处输入图片描述

您将在每个describeit上方有调试/运行选项。

在此处输入图片描述

您可以在Visual Studio Code中打开测试文件并单击其中一个选项。

一个简单的解决方案:

yarn test -g fileName

npm test -g fileName

示例:

yarn test -g cancelTransaction

npm test -g cancelTransaction

更多关于测试过滤器:

Test Filters
--fgrep, -f Only run tests containing this string [string]
--grep, -g Only run tests matching this string or regexp [string]
--invert, -i Inverts --grep and --fgrep matches [boolean]

简单的方法是运行单个单元测试文件,就是在根文件夹里面的终端运行命令。

npm test <fileName.test.js>


// For example
npm test utils.test.js


我还尝试了Visual Studio Code的Jest Runner扩展,效果很好。

要在特定文件中运行特定测试:

yarn test -f "partial-filename" -t "as split node"

npm testjest可以替换yarn test,具体取决于您首选的JS捆绑器。

这只会尝试在包含some-partial-filename的文件中查找测试,并且在这些文件中,测试需要有一个describeit指令,其中提到“作为拆分节点”,例如

// In cool-partial-filename.js
describe("with a less indented sibling", () => {
it("should create a new check-list-item with the same indent as split node", () => {
console.log("This would run with the invocation above");
})
})

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

npx jest foo.test.js

package.json:

  "scripts": {
"test": "jest --coverage",
"start": "node index.js"
}

以下内容为我工作:

npm test -f comm -- -t=first

它将在其文件名中找到所有包含“comm”的文件,并仅在找到的文件中运行包含“first”的测试。

Jest和Jest Runner在您处理jest时是非常有用的VSCode扩展。

Jest一个自动测试运行器

JestRunner在测试上方添加“运行|调试”代码透镜以运行或调试单个测试。

运行|调试

使用此命令:

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

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

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

编辑: 找到了另一种方法来做到这一点。 #用于功能测试的EYZ0
#集成测试EYZ0

用package.json剧本

package.json中的"scripts": { "test": "jest" }

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

直接使用jest-cli

全球安装:

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

如果您正在使用纱线,请执行此操作

yarn test nameofthefile

eg:

yarn test file.test.js

只需使用此命令运行并检查特定文件的覆盖范围。

yarn run test Index.js -u --coverage --watchAll=false