我能够使用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'


当前回答

我们在Angular中使用了nrwl-nx。在这种情况下,我们可以使用这个命令:

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

注:

npm test will run the test script specified in package.json: "test": "ng test" --: tells npm to pass the following parameters to the test script (instead of consuming them) 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.json navigate 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 <ng-project> -- --help to see all available options Or check the online documentation One of the options is --testFile which is used here

其他回答

一个简单可行的解决方案:

yarn test -g文件名或

npm test -g fileName

例子:

yarn 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]

当时我用的是:

yarn test TestFileName.spec.js

你不应该输入完整路径。对我来说,这在Windows 10电脑上是可行的。

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

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

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

}

运行单个测试:

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

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