我正在使用 jest 进行测试,目前我可以忽略 node_modules。然而,问题是我想用 babel 转译的 node_modules 中有 1 个包。现在我忽略的模式是这样的:
testPathIgnorePatterns: ['./node_modules/'],
如果我的包名为“my-package”,我怎样才能使 testPathIgnorePatterns 不忽略 node_modules 中的包?
最佳答案
TL;DR - 将此配置键与此正则表达式一起使用:
transformIgnorePatterns: ['/node_modules\/(?!my-package)(.*)']
这是一个由两部分组成的答案。
第 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)(.*)']
这基本上就是说,忽略除 my-package 之外的所有 node_modules。但是,这里需要注意的是,testPathIgnorePatterns
并不能决定一个模块是否应该被 babel 转译。这个键是为了 Jest 知道你的测试文件在哪里。基本上,使用这个键,你是在开 Jest 说“不要在 node_modules
中查找扩展名为 .test.js
的文件”,因为你不想运行导入的 node_module 包的测试。
所以,实际上,你想完全忽略这个设置,因为 jest 会自动将它默认为 ['/node_modules/']
,或者如果你想添加其他路径来忽略,你' d 需要:
testpathIgnorePatterns: ['other/file/path', '/node_modules/']
第 2 部分 - 在哪里使用正则表达式
鉴于第 1 部分的上下文,放置正则表达式以允许 jest 从 node_modules 转译特定包的正确位置是:transformIgnorePatterns
。所以它看起来像这样:
transformIgnorePatterns: ['/node_modules\/(?!my-package)(.*)']
这样,jest 将不会转译除“my-package”之外的任何 node_modules 包。我相信上面提到的两个键的默认值都是“node_modules”——意思是,node_modules 在 testPath
和 transform
关于testing - 开 Jest 忽略除 1 个包之外的所有 node_modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086182/