testing - 开 Jest 忽略除 1 个包之外的所有 node_modules

标签 testing jestjs babeljs

我正在使用 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 在 testPathtransform

中都被自动忽略了

Jest docs for these configuration settings

关于testing - 开 Jest 忽略除 1 个包之外的所有 node_modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086182/

相关文章:

.net - .NET 中的代码约定、测试、断言和异常,何时使用?

reactjs - 使用 react-testing-library 测试 useContext()

typescript - ESlint import/no-unresolved with Babel plugin root import

testing - 无法实例化规范 'KernelTest'

testing - Protractor Vs Suitest vs Cypress 哪种框架更适合大型角度应用程序?

testing - 按函数名称进行基准测试

javascript - 在 Jest 单元测试中访问 React 组件中的 mobx 可观察属性

typescript - 为什么我的 Jest 函数模拟会影响另一个测试

node.js - Webstorm 意外 token 导出

reactjs - 我的测试无法与带有 typescript 的 react 测试库一起使用