我能够使用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安装为全局,运行Jest myFileToTest.spec.js,它工作了。

其他回答

Jest将使用您传递的内容作为正则表达式模式。它会匹配。

如果您想运行一个特定的测试文件,那么最好的方法是使用它的精确完整路径。(你也可以指定一个特定的相对路径,比如(src/XFolder/index.spec.ts))。

在Linux中提供目录中完整路径的最简单方法是:

jest $PWD/index.spec.ts

注意变量$PWD的使用。

对于Windows !(待更新)

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

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]

不需要传递完整的路径。只需使用正则表达式模式。

看到——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

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

npm test -- fileName.jsx 

你有两个选择:

Option 1: Command line. 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. 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. 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.