ChatGPT解决这个技术问题 Extra ChatGPT

如何使用 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'

如果您想在后台查看变化,请使用 npx jest Foo.test.js 使用 --watchAll,例如 npx jest --watchAll Foo.test.js

i
icc97

至少从 2019 年开始:

npm test -- bar.spec.js

2015 年:

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

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

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


不幸的是,这对我不起作用。运行 jest bar.spec.js 给出 jest: command not found。我已确认已安装 Jest(npm list -g jest 显示 jest@0.1.37)。 FWIW,当我使用 npm test 运行时,它使用 jest-cli
是的,jest-cli 是正确的模块,全局安装它npm install -g jest-cli。 npm 中的 jest 是... something else
这是不正确的。 npm test working 并不意味着 jest 是全局安装的。这只是意味着 jest 已安装在您的项目中。
就像@ChiedoJohn 说的那样。要在不全局安装的情况下运行它,您可以从应用的根目录运行它:node_modules/.bin/jest args
如果您使用默认的 jasmine 设置,您可以使用 fit 而不是 it 来集中单个测试。
P
Peter Mortensen

你所要做的就是念诵魔法咒语:

npm test -- SomeTestFileToRun

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

npm test -- --help

无论如何,念经

npm test -- Foo

在指定文件 (FooBar.js) 中运行测试。但是,您应该注意:

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

Jest 似乎将规范视为前缀。

所以上面的咒语会

运行 FooBar.js、Foo.js 和 FooZilla.js

但不运行 foo.js


谢谢,不幸的是我在运行这个时遇到了同样的错误:npm ERR! Error: ENOENT, open '<path to project>/node_modules/<name of file>/package.json'
除了命令行,还有其他方法可以运行开玩笑测试吗? ,好像我向我现有的项目 rest api 发出 post 请求,它会给我 CSRF 令牌问题。至于我将如何为我现有的项目设置笑话测试?这样它将开始使用“/rest-api”而不是“localhost:8000/rest-api”来服务请求
@SuyogSawant:这不是评论。这本身就是一个问题。你应该在 StackOverflow 上问它。
在我的情况下,简单的 npm test ToDoForm.test.js 有效,而 jest ToDoForm.test.js 没有
对于 Windows,您需要为文件路径键入双反斜杠。例如:纱线运行测试 src\\tests\\actions\\auth.test.js
P
Peter Mortensen

要运行单个测试:

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

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


P
Peter Mortensen

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

https://i.stack.imgur.com/OMXNT.png

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

https://i.stack.imgur.com/xDtz0.png

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


这是“宾果!”。很好的建议,谢谢。
P
Peter Mortensen

如果您使用 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",
    ...
  },

}

您也可以使用 yarn test SomeRegexHere 来保存输入,例如 yarn test MyClass。但是,请注意,截至 2021 年 12 月 4 日,正则表达式与绝对路径匹配,因此您的模式可能与包含您的源树的文件夹名称匹配。请参阅github.com/facebook/jest/issues/8226
m
mikemaccana

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

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

npx jest [file or directory]

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


node_modules/.bin 中执行二进制文件的快捷方式是使用 npx 命令。例如 npx jest [args]
值得指出的是@Aerohil 并没有错过这一点;该命令在 2016 年不存在;我更新了答案
A
Ahmed Ashour

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

npm test -- fileName.jsx 

T
TmTron

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

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

笔记:

npm test 将运行 package.json 中指定的测试脚本:“test”:“ng test”

--:告诉 npm 将以下参数传递给测试脚本(而不是使用它们)

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

是 angular.json 中的项目名称,省略此参数时,将使用“defaultProject”(在 angular.json 中指定)(因此必须指定它,当测试不在您的默认值时)项目)

当您省略此参数时,将使用“defaultProject”(在 angular.json 中指定)(因此,当测试不在您的默认项目中时,您必须指定它)

接下来我们必须检查使用了哪个构建器:在 angular.json 中导航到“project”-“”-“architect”-“test”并检查“builder”,在我们的例子中是:“@nrwl /开玩笑:开玩笑”

在 angular.json 中导航到“项目”-“”-“建筑师”-“测试”

并检查“builder”,在我们的例子中是:“@nrwl/jest:jest”

现在我们知道了构建器,我们需要找到可用的 cmd-line 参数 在命令行上,运行 npm test -- --help 以查看所有可用选项或查看在线文档

在命令行上,运行 npm test -- --help 以查看所有可用选项

或查看在线文档

选项之一是 --testFile ,这里使用


w
wbharding

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

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

P
Peter Mortensen

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


P
Peter Mortensen

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

jest --findRelatedTests path/to/fileA.js

参考 (Jest CLI Options)

如何在 Nx monorepo 中实现这一点?这是答案(在目录 /path/to/workspace 中):

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

参考资料更多信息:How to test a single Jest test file in Nx #6


P
Peter Mortensen

当时,我通过使用:

yarn test TestFileName.spec.js

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


k
king_leo

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

npx jest foo.test.js

S
Spencer

使用 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 option 具有将路径作为未命名的位置参数传递给 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

P
Peter Mortensen

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

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

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


P
Peter Mortensen

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

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]

P
Peter Mortensen

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

npm test <fileName.test.js>

// For example
npm test utils.test.js

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


N
Natan Farkash

使用这个命令:

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

G
Gitesh kumar Jha

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

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

编辑:找到另一种方法。
npm run test:functional -i file-name 用于功能测试
npm run test:integration -i file-name 用于集成测试


W
W.Perrin

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

请参阅 --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

J
Jack Steam

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

Jest 自动测试运行器

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

https://i.stack.imgur.com/S2fmJ.png


仅链接的响应可以作为评论,但不能作为答案。答案必须是自包含的,并且必须嵌入解决问题所需的确切代码。链接是完全可以接受的,但必须嵌入来自链接的相关信息。没有人愿意点击盲链接,重要的是,如果网站无法访问或内容发生变化,您的响应将变得毫无用处。
P
Peter Mortensen

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


这非常简单。谢谢你
B
Byusa

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

yarn test nameofthefile

例如:

yarn test file.test.js

P
Peter Mortensen

你有两个选择:

选项 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。它不仅允许您逐个文件地运行测试,甚至可以通过右键单击要运行的测试来运行特定的套件和规范。


P
Peter Mortensen

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

但是我怎样才能将它连接到 vscode,例如进行调试?
P
Peter Mortensen

来自 Jest 文档:

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

运行这个

 npm run test

M
Manik Kumar

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

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

P
Peter Mortensen

Jest 将使用您传递的内容作为 regular expression 模式。它将匹配。

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

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

jest $PWD/index.spec.ts

注意变量 $PWD 的使用。

https://i.stack.imgur.com/fHKVh.png

对于 Windows! (要被更新)


P
Peter Mortensen
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'

一个解释将是有序的。例如,它应该实现什么?第一部分是文件 LoggerService.test.ts 的内容吗?
P
Peter Mortensen

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

OP 不是在询问 NestJS,而是在询问 Jest。