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


当前回答

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

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

npx jest [file or directory]

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

其他回答

在Angular和Jest中,你可以把它添加到文件包中。“scripts”下的Json:

"test:debug": "node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand"

然后,要为特定文件运行单元测试,可以在终端中写入此命令

npm run test:debug modules/myModule/someTest.spec.ts

用一个包裹。json脚本

在package.json中使用"scripts": {"test": "jest"}:

npm test -- foo/__tests__/bar.spec.js

直接使用jest-cli

Globally-installed:

jest foo/__tests__/bar.spec.js

本地安装:

./node_modules/.bin/jest foo/__tests__/bar.spec.js

使用——testPathPattern

testPathPattern选项具有将路径作为未命名的位置参数传递给jest-cli的等效效果。看到normalize.ts。

./node_modules/.bin/jest --testPathPattern foo/__tests__/bar.spec.js

测试两个或多个特定文件

文件名用逗号或空格分隔:

./node_modules/.bin/jest foo/__tests__/bar.spec.js,foo/__tests__/foo.spec.js
./node_modules/.bin/jest foo/__tests__/bar.spec.js foo/__tests__/foo.spec.js

多次传递——testPathPattern:

./node_modules/.bin/jest --testPathPattern foo/__tests__/bar.spec.js --testPathPattern foo/__tests__/foo.spec.js

使用该命令:

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

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

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

你所要做的就是念咒语

npm test -- SomeTestFileToRun

standalone——是*nix的魔法,用于标记选项的结束,这意味着(对于NPM)之后的所有内容都传递给正在运行的命令,在这种情况下是玩笑。顺便说一句,您可以这样显示Jest的使用说明

npm test -- --help

总之,高喊

npm test -- Foo

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

Jest将名称视为区分大小写的,因此如果您正在使用不区分大小写但保留大小写的文件系统(如Windows NTFS),则可能会遇到奇怪的情况。 Jest似乎将规范视为前缀。

所以上面的咒语会

运行FooBar.js, Foo.js和FooZilla.js 但不是运行foo.js