开玩笑忽略除 1 个包之外的所有 node_modules

dux*_*x-- 4 testing jestjs babeljs

我正在使用 jest 进行测试,目前我可以忽略 node_modules。然而,问题是 node_modules 中有 1 个包,我想用 babel 进行转换。现在我忽略的模式如下所示:

testPathIgnorePatterns: ['./node_modules/'],
Run Code Online (Sandbox Code Playgroud)

如果我的包被称为“我的包”,我怎样才能让 testPathIgnorePatterns 不会忽略 node_modules 中的那个?

dux*_*x-- 5

TL;DR - 将此配置键与此正则表达式一起使用:

transformIgnorePatterns: ['/node_modules\/(?!my-package)(.*)']
Run Code Online (Sandbox Code Playgroud)

这是一个 2 部分的答案。

第1部分

testPathIgnorePatterns键采用字符串/正则表达式数组,因此我可以传递一个正则表达式,该正则表达式将匹配除我想要的所有 node_modules 之外的所有节点模块,如下所示:

// one way to do it
testpathIgnorePatterns: ['/node_modules\/(?!my-package).+\.js$']

// another way to do it - this regex seems simpler to me
testpathIgnorePatterns: ['/node_modules\/(?!my-package)(.*)']
Run Code Online (Sandbox Code Playgroud)

这基本上是说,忽略除 my-package 之外的所有 node_modules。但是,这里要注意的是,testPathIgnorePatterns并不能确定模块是否应该被 babel 转译。这个键是为了知道你的测试文件在哪里。基本上,使用这个键,你告诉 jest '不要查找node_modules带有.test.js扩展名的文件',因为你不想运行导入的 node_module 包的测试。

因此,实际上,您想完全忽略此设置,因为 jest 会自动将其默认为['/node_modules/'],或者如果您想添加其他要忽略的路径,则需要:

testpathIgnorePatterns: ['other/file/path', '/node_modules/']
Run Code Online (Sandbox Code Playgroud)

第2部分

由于从第1部分的背景下,正确的位置放正则表达式允许开玩笑到transpile特定软件包从node_modules是:transformIgnorePatterns。所以它看起来像这样:

transformIgnorePatterns: ['/node_modules\/(?!my-package)(.*)']
Run Code Online (Sandbox Code Playgroud)

这样,jest 不会转译除“my-package”之外的任何 node_modules 包。我相信上面提到的两个键的默认值都是“node_modules”——意思是,node_modules 在testPathtransform

这些配置设置的 Jest 文档