繁体   English   中英

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

[英]How do I test a single file using Jest?

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

我有:

  • 运行npm install jest-cli --save-dev
  • 更新了package.json : `{ ... "scripts": { "test": "jest" } ... }
  • 写了一些测试。

运行npm test按预期工作(目前它运行 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'

至少从 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 将名称视为区分大小写,因此如果您使用不区分大小写但保留大小写的文件系统(如 Windows NTFS ),您可能会遇到看起来很奇怪的事情。

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

所以上面的咒语会

  • 运行FooBar.jsFoo.jsFooZilla.js
  • 运行foo.js

要运行单个测试:

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

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

如果你使用Yarn ,你可以在后面直接添加.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 test并不意味着 Jest 是全局安装的。 它只是意味着“测试”被映射到在你的package.json文件中使用 Jest。

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

npx jest [file or directory]

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

如果您安装 Visual Studio Code 插件Jest Runner

在此处输入图像描述

您将在每个describeit上方都有Debug / Run选项。

在此处输入图像描述

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

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

npm test -- fileName.jsx 

我们将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"
    • 现在我们知道了构建器,我们需要找到可用的命令行参数
      • 在命令行上,运行npm test <ng-project> -- --help以查看所有可用选项
      • 或查看在线文档
    • 选项之一是--testFile ,这里使用

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

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

npm test或者jest可以替换yarn test ,这取决于你喜欢的 JS bundler。

这只会尝试在包含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");
  })
})

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

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

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

当时,我通过使用:

yarn test TestFileName.spec.js

你不应该输入完整的路径。 这适用于我在 Windows 10 机器上。

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

npx jest foo.test.js

使用 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

这就是我在不重新启动测试的情况下对特定文件动态运行测试的方式。

我的 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

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

一个有效的简单解决方案:

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 Extensions,效果很好。

使用这个命令:

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

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

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

编辑:找到另一种方法。
npm run test:functional -i file-name
npm run test:integration -i file-name

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

请参阅--testLocationInResults

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

当您使用 jest 时,Jest 和 Jest Runner 是非常有用的 VSCode 扩展。

Jest一个自动测试运行器

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

“运行|调试”代码镜头

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

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

yarn test nameofthefile

例如:

yarn test file.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。 您使用项目使用的笑话。

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

使用 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

Jest文档中:

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

运行这个

 npm run test

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

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

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

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

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

jest $PWD/index.spec.ts

注意变量$PWD的使用。

在此处输入图像描述

对于 Windows! (要被更新)

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

使用 package.json:

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

以下对我有用:

npm test -f comm -- -t=first

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

“测试”:“开玩笑 api/ds_server/ds_server.test.js”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM