简体   繁体   English

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

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

I am able to test multiple files using Jest, but I cannot figure out how to test a single file.我可以使用 Jest 测试多个文件,但我不知道如何测试单个文件。

I have:我有:

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

Running npm test works as expected (currently it runs 14 tests).运行npm test按预期工作(目前它运行 14 个测试)。

How do I test a single file, eg test app/foo/__tests__/bar.spec.js ?如何测试单个文件,例如 test app/foo/__tests__/bar.spec.js

I have tried running npm test app/foo/__tests__/bar.spec.js (from the project root), but I get the following error:我曾尝试运行npm test app/foo/__tests__/bar.spec.js (从项目根目录),但我收到以下错误:

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

Since at least 2019:至少从 2019 年开始:

npm test -- bar.spec.js

In 2015: 2015 年:

In order to run a specific test, you'll need to use the jest command.为了运行特定的测试,您需要使用jest命令。 npm test will not work. npm test将不起作用。 To access jest directly on the command line, install it via npm i -g jest-cli or yarn global add jest-cli .要直接在命令行上访问jest ,请通过npm i -g jest-cliyarn global add jest-cli安装它。

Then simply run your specific test with jest bar.spec.js .然后只需使用jest bar.spec.js运行您的特定测试。

Note : You don't have to enter the full path to your test file.注意:您不必输入测试文件的完整路径。 The argument is interpreted as a regular expression.该参数被解释为正则表达式。 Any part of the full path that uniquely identifies a file suffices.唯一标识文件的完整路径的任何部分都足够了。

All you have to do is chant the magic incantation:你所要做的就是念诵魔法咒语:

npm test -- SomeTestFileToRun

The stand-alone -- is *nix magic for marking the end of options, meaning (for NPM) that everything after that is passed to the command being run, in this case jest .独立的--是 *nix 用于标记选项结束的魔法,这意味着(对于 NPM)之后的所有内容都传递给正在运行的命令,在本例中为jest As an aside, you can display Jest usage notes by saying顺便说一句,您可以通过说来显示 Jest 使用说明

npm test -- --help

Anyhow, chanting无论如何,念经

npm test -- Foo

runs the tests in the named file ( FooBar.js ).在命名文件 ( FooBar.js ) 中运行测试。 You should note, though, that:但是,您应该注意:

  • Jest treats the name as case-sensitive, so if you're using a case-insensitive, but case-preserving file system (like Windows NTFS ), you might encounter what appears to be oddness going on. Jest 将名称视为区分大小写,因此如果您使用不区分大小写但保留大小写的文件系统(如 Windows NTFS ),您可能会遇到看起来很奇怪的事情。

  • Jest appears to treat the specification as a prefix. Jest 似乎将规范视为前缀。

So the above incantation will所以上面的咒语会

  • Run FooBar.js , Foo.js and FooZilla.js运行FooBar.jsFoo.jsFooZilla.js
  • But not run foo.js运行foo.js

To run an individual test:要运行单个测试:

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

-t - after it, put a regular expression containing the test name. -t - 在它之后,放置一个包含测试名称的正则表达式

If you use Yarn , you can add the .spec.js or .test.js file directly after:如果你使用Yarn ,你可以在后面直接添加.spec.js.test.js文件:

yarn test src/lib/myfile.test.js

This is the part from my package.json file with Jest installed as a local package (removed the relevant parts):这是我的package.json文件中的一部分,其中 Jest 作为本地包安装(删除了相关部分):

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

}

Using npm test doesn't mean Jest is installed globally.使用npm test并不意味着 Jest 是全局安装的。 It just means "test" is mapped to using Jest in your package.json file.它只是意味着“测试”被映射到在你的package.json文件中使用 Jest。

The following works, at the root level of the project:以下工作,在项目的根级别:

npx jest [file or directory]

file or directory can be the test file you want to run or the directory containing multiple files. file or directory可以是您要运行的测试文件或包含多个文件的目录。

If you install the Visual Studio Code plugin Jest Runner ,如果您安装 Visual Studio Code 插件Jest Runner

在此处输入图像描述

You will have Debug / Run options above every describe and it .您将在每个describeit上方都有Debug / Run选项。

在此处输入图像描述

You can open your test file in Visual Studio Code and click on one of those options.您可以在 Visual Studio Code 中打开您的测试文件,然后单击其中一个选项。

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

npm test -- fileName.jsx 

We are using nrwl-nx with Angular .我们将nrwl-nxAngular一起使用。 In this case we can use this command:在这种情况下,我们可以使用以下命令:

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

Notes:笔记:

  • npm test will run the test script specified in package.json : "test": "ng test" npm test将运行package.json中指定的测试脚本: "test": "ng test"
  • -- : tells npm to pass the following parameters to the test script (instead of consuming them) -- :告诉 npm 将以下参数传递给测试脚本(而不是使用它们)
  • Thus the rest of the cmd will be passed to ng test因此 cmd 的其余部分将传递给ng test
    • <ng-project> is the name of a project in angular.json <ng-project>angular.json中的项目名称
      • when you omit this parameter, the "defaultProject" (specified in angular.json ) will be used (so you must specify it, when the test is not in your default project)当您省略此参数时,将使用"defaultProject" (在angular.json中指定)(因此,当测试不在您的默认项目中时,您必须指定它)
    • Next we must check which builder is used:接下来我们必须检查使用了哪个构建器:
      • In angular.json navigate to "project" - "<ng-project>" - "architect" - "test"angular.json导航到"project" - "<ng-project>" - "architect" - "test"
      • and check the "builder" , which in our case is: "@nrwl/jest:jest"并检查"builder" ,在我们的例子中是: "@nrwl/jest:jest"
    • Now that we know the builder, we need to find the available cmd-line parameters现在我们知道了构建器,我们需要找到可用的命令行参数
      • On the command line, run npm test <ng-project> -- --help to see all available options在命令行上,运行npm test <ng-project> -- --help以查看所有可用选项
      • Or check the online documentation或查看在线文档
    • One of the options is --testFile which is used here选项之一是--testFile ,这里使用

To run a specific test in a specific file:要在特定文件中运行特定测试:

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

npm test , or jest can replace yarn test , depending on your preferred JS bundler. npm test或者jest可以替换yarn test ,这取决于你喜欢的 JS bundler。

This would only attempt to find tests in files that contained some-partial-filename , and within those files, the test would need to have a describe or it directive that mentions "as split node", for example这只会尝试在包含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。

It can also be achieved by:也可以通过以下方式实现:

jest --findRelatedTests path/to/fileA.js

Reference ( Jest CLI Options )参考( Jest CLI 选项

How can that be achieved in the Nx monorepo?如何在 Nx monorepo 中实现这一点? Here is the answer (in directory /path/to/workspace ):这是答案(在目录/path/to/workspace ):

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

Reference & more information: How to test a single Jest test file in Nx #6参考和更多信息:如何在 Nx #6 中测试单个 Jest 测试文件

At that time, I did it by using:当时,我通过使用:

yarn test TestFileName.spec.js

You shouldn't put in the complete path.你不应该输入完整的路径。 That works for me on a Windows 10 machine.这适用于我在 Windows 10 机器上。

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

npx jest foo.test.js

With a package.json script使用 package.json 脚本

With "scripts": { "test": "jest" } in package.json:使用 package.json 中的"scripts": { "test": "jest" }

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

Using jest-cli directly直接使用 jest-cli

Globally-installed:全球安装:

jest foo/__tests__/bar.spec.js

Locally-installed:本地安装:

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

Using --testPathPattern使用--testPathPattern

The --testPathPattern option has the equivalent effect of passing paths as unnamed positional arguments to jest-cli. --testPathPattern选项具有将路径作为未命名位置参数传递给 jest-cli 的等效效果。 See normalize.ts .请参阅normalize.ts

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

Testing two or more specific files测试两个或更多特定文件

Separate filenames with commas or spaces:用逗号或空格分隔文件名:

./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

Pass --testPathPattern multiple times:通过--testPathPattern多次:

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

This is how I dynamically run tests on a specific file without restarting the test.这就是我在不重新启动测试的情况下对特定文件动态运行测试的方式。

My React project was created as create-react-app .我的 React 项目被创建为create-react-app

So it watches test for changes, automatically running test when I make changes.所以它监视测试的变化,当我做出改变时自动运行测试。

So this is what I see at the end of the test results in the terminal:所以这就是我在终端测试结果结束时看到的:

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.

Press WW

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.

Then press P然后按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.

This is after I wanted to run the 'index.es6.js' file in the 'Login' folder:这是在我想在“登录”文件夹中运行“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

That's how I run tests on a specific file.这就是我在特定文件上运行测试的方式。

A simple solution that works:一个有效的简单解决方案:

yarn test -g fileName or yarn test -g fileName

npm test -g fileName

Example:例子:

yarn test -g cancelTransaction or yarn test -g cancelTransaction

npm test -g cancelTransaction

More about test filters:有关测试过滤器的更多信息:

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]

The simple way is to run a single unit test file, is inside the root folder run the command in the terminal.简单的方法是运行单个单元测试文件,就是在终端的根文件夹里面运行命令。

npm test <fileName.test.js>

// For example
npm test utils.test.js

I have also tried the Jest Runner Extensions for Visual Studio Code, and it works great.我还尝试了 Visual Studio Code 的 Jest Runner Extensions,效果很好。

使用这个命令:

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

The below command worked for me.下面的命令对我有用。
npx jest -i file-name

No need to specify complete path of the file, filename is sufficient.不需要指定文件的完整路径,文件名就足够了。

Edit : Found another way to do it.编辑:找到另一种方法。
npm run test:functional -i file-name for Functional Test npm run test:functional -i file-name
npm run test:integration -i file-name for Integration Test npm run test:integration -i file-name

There isn't any need to pass the full path.无需传递完整路径。 Just use a regular expression pattern.只需使用正则表达式模式。

See --testLocationInResults .请参阅--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 and Jest Runner are super useful VSCode extensions when you working on jest.当您使用 jest 时,Jest 和 Jest Runner 是非常有用的 VSCode 扩展。

Jest An automatic test runner Jest一个自动测试运行器

Jest Runner Adds "Run | Debug" code lens above the test to run or debug a single test. Jest Runner在测试上方添加“运行|调试”代码镜头以运行或调试单个测试。

“运行|调试”代码镜头

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

Do this if you are using yarn如果您使用纱线,请执行此操作

yarn test nameofthefile

eg:例如:

yarn test file.test.js

You have two options:你有两个选择:

  • Option 1: Command line.选项 1:命令行。 You can run the following command您可以运行以下命令

    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'

    This avoids you to install Jest globally.这可以避免您全局安装 Jest。 You use the jest used by your project.您使用项目使用的笑话。

  • Option 2: If you are using Visual Studio Code you have a great plugin to do this: Jest Runner .选项 2:如果您使用的是Visual Studio Code ,那么您有一个很棒的插件可以做到这一点: Jest Runner It allows you not only to run tests file by file, but even specific suites and specs just by a right click on the tests you want to run.它不仅允许您逐个文件地运行测试,甚至可以通过右键单击要运行的测试来运行特定的套件和规范。

With Angular and Jest you can add this to file package.json under "scripts":使用 Angular 和 Jest,您可以将其添加到“脚本”下的文件package.json中:

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

Then to run a unit test for a specific file you can write this command in your terminal然后要对特定文件运行单元测试,您可以在终端中编写此命令

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

From the Jest documentation:Jest文档中:

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

Run this with运行这个

 npm run test

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

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

Jest will use what you pass as a regular expression pattern. Jest将使用您传递的内容作为正则表达式模式。 That it will match for.它将匹配。

If you want to run a specific test file, then the best way to do it is to use the precise full path to it.如果要运行特定的测试文件,那么最好的方法是使用它的精确完整路径。 (You can too specify a certain relative path like (src/XFolder/index.spec.ts)). (您也可以指定某个相对路径,例如 (src/XFolder/index.spec.ts))。

The easiest way to provide the full path being in the directory and in Linux is:在目录和 Linux 中提供完整路径的最简单方法是:

jest $PWD/index.spec.ts

Note the use of the variable $PWD .注意变量$PWD的使用。

在此处输入图像描述

For Windows!对于 Windows! (to be updated) (要被更新)

import LoggerService from '../LoggerService ';

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

Usage:用法:

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

For NestJS users, the simple alternative is to use,对于NestJS用户,简单的替代方法是使用,

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

NestJS comes preconfigured with the regex of the test files to search for in case of Jest. NestJS 预先配置了测试文件的正则表达式,以便在 Jest 的情况下进行搜索。

A simple example is -一个简单的例子是——

npm test -t app-util.spec.ts

(that is my .spec file name) (这是我的 .spec 文件名)

The complete path need not be given since Jest searches for .spec files based on the configuration which is available by default in case of NestJS:不需要给出完整路径,因为 Jest 会根据NestJS的默认配置搜索 .spec 文件:

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

With a package.json:使用 package.json:

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

The following worked for me:以下对我有用:

npm test -f comm -- -t=first

It will find all files containing 'comm' in its filename and only run tests containing 'first' in the found files.它将查找文件名中包含“comm”的所有文件,并且只运行找到的文件中包含“first”的测试。

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

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

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