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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28725955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:28:59  来源:igfitidea点击:

How do I test a single file using Jest?

node.jsjestjs

提问by Musket

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
  • Updated package.json: `{ ... "scripts": { "test": "jest" } ... }
  • Written a number of tests.
  • npm install jest-cli --save-dev
  • 更新package.json:`{ ... "scripts": { "test": "jest" } ... }
  • 写了一些测试。

Running npm testworks as expected (currently it runs 14 tests).

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

How do I test a single file, e.g. 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 project root), but I get the following error:

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

npm ERR! Error: ENOENT, open '<path to project>/node_modules/app/foo/__tests__/bar.spec.js/package.json'

Thanks

谢谢

采纳答案by ncuillery

In order to run a specific test, you'll need to use the jestcommand. npm testwill not work. To access jestdirectly on the command line, install it via npm i -g jest-clior yarn global add jest-cli.

为了运行特定的测试,您需要使用该jest命令。npm test不管用。要jest直接在命令行上访问,请通过npm i -g jest-cli或安装它yarn 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 regexp. Any part of the full path that uniquely identifies a file suffices.

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

回答by Nicholas Carey

All you have to do is chant the magick incantation:

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

npm test -- SomeTestFileToRun

The standalone --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. As an aside, you can display jest usage notes by saying

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

npm test -- --help

Anyhow, chanting

无论如何,念诵

npm test -- Foo

runs the tests in the named file (FooBar.js). You should note, though, that:

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

  • 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 appears to treat the spec as a prefix.

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

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

So the above incantation will

所以上面的咒语将

  • Run FooBar.js, Foo.jsand FooZilla.js
  • But NOT run foo.js
  • 运行FooBar.jsFoo.jsFooZilla.js
  • 但不运行 foo.js

回答by cabaji99

To run individual test:

运行单个测试:

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

-t- after it put a regexcontaining the test name.

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

回答by AeroHil

Using npm testdoesn't mean jest is install globally. It just means "test" is mapped to using jest in your package.json

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

The following is what worked for me, at the root level of the project:

以下是在项目的根级别对我有用的内容:

node_modules/.bin/jest [args]

args can be the test file you want to run or the directory containing multiple files.

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

回答by Andreas Heissenberger

if you use yarnyou can add the .spec.jsor .test.jsfile directly after:

如果您使用,yarn您可以在以下之后直接添加.spec.js.test.js文件:

yarn test src/lib/myfile.test.js

This is the part from my package.jsonwith jest install as a local package (removed the relevant parts):

这是我的package.jsonwith jest install 作为本地包的部分(删除了相关部分):

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

}

回答by Hilal Aissani

You could use the file name with npm test --:

您可以使用文件名npm test --

npm test -- fileName.jsx 

回答by bmaggi

If you running npm >= 5.2.0and you have installed jest locally as a devDependencieswith npm i -d jestyou can run jest on a particular file by doing npx jest /path/to/your/spec.js

如果您正在运行npm >= 5.2.0并且您已经在本地安装了 jest devDependenciesnpm i -d jest那么您可以通过执行以下操作在特定文件上运行 jestnpx jest /path/to/your/spec.js

回答by TmTron

We are using nrwl-nxwith angular. In this case we can use this command:

我们正在使用nrwl-nxangular。在这种情况下,我们可以使用以下命令:

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

notes:

笔记:

  • npm testwill run the test script specified in package.json: "test:client": "ng test client"
  • thus the rest of the cmd will be passed to ng test
    • <ng-project>is the name of a project in 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)
    • next we must check which builder is used:
      • in angular.jsonnavigate to "project"- "<ng-project>"- "architect"- "test"
      • and check the "builder", which in our case is: "@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 server -- --helpto see all available options
      • or check the online docs
    • one of the options is --testFilewhich is used here
  • npm test将运行中指定的测试脚本package.json"test:client": "ng test client"
  • 因此其余的 cmd 将传递给ng test
    • <ng-project>是一个项目的名称 angular.json
      • 当您省略此参数时"defaultProject"(在 中指定angular.json)将被使用(因此您必须指定它,当测试不在您的默认项目中时)
    • 接下来我们必须检查使用了哪个构建器:
      • angular.json导航到"project"- "<ng-project>"- "architect"-"test"
      • 并检查"builder",在我们的例子中是:"@nrwl/jest:jest"
    • 现在我们知道了构建器,我们需要找到可用的 cmd-line 参数
      • 在命令行上,运行npm test server -- --help以查看所有可用选项
      • 或查看在线文档
    • 其中一个选项是--testFile这里使用的

回答by SohelAhmedM

Also can be achieved by

也可以通过

$ jest --findRelatedTests path/to/fileA.js

$ jest --findRelatedTests path/to/fileA.js

ref (https://jestjs.io/docs/en/cli#running-from-the-command-line)

参考(https://jestjs.io/docs/en/cli#running-from-the-command-line

How can that be achieved in Nx monorepo, here is the answer

如何在 Nx monorepo 中实现这一点,这是答案

user@host:/path/to/workspace$ npx nx test api --findRelatedTests=apps/api/src/app/mytest.spec.ts

user@host:/path/to/workspace$ npx nx test api --findRelatedTests=apps/api/src/app/mytest.spec.ts

ref & more info (https://github.com/satminav/nx-qa/issues/6)

参考及更多信息(https://github.com/satminav/nx-qa/issues/6

回答by deko

This is how i dynamically run tests on specific file without restarting the test. My react project was created was create-react-app

这就是我在不重新启动测试的情况下对特定文件动态运行测试的方式。我的反应项目被创建是create-react-app

so it watchs test for changes, automatically running test when I make changes.

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

So this is what I see at the end of the test results on 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 W

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

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

Thats how I run tests on specific file.

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