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

我有:

执行npm install jest-cli——save-dev命令 更新包。Json: '{…"scripts": {"test": "jest"}…} 编写了许多测试。

运行npm测试可以正常工作(目前运行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'


当前回答

来自Jest文档:

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

使用

 npm run test

其他回答

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

你将有调试/运行选项上面的每个描述和它。

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

这就是如何在不重新启动测试的情况下动态地运行特定文件上的测试。

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

这是在我想运行'Login'文件夹中的'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

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

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

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

npx jest [file or directory]

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

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

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,你可以在下面直接添加.spec.js或.test.js文件:

yarn test src/lib/myfile.test.js

这是我包裹里的零件。Jest作为本地包安装在json文件中(删除了相关部分):

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

}