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


当前回答

使用package.json:

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

下面的方法对我很有效:

npm test -f comm -- -t=first

它会找到文件名中包含“comm”的所有文件,只运行找到的文件中包含“first”的测试。

其他回答

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

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]

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

npm test <fileName.test.js>

// For example
npm test utils.test.js

我也尝试了Jest Runner扩展的Visual Studio代码,它工作得很好。

使用该命令:

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

我只是将Jest安装为全局,运行Jest myFileToTest.spec.js,它工作了。

你可以使用npm test的文件名——

npm test -- fileName.jsx