Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jest 测试相关配置 #36

Open
ChelesteWang opened this issue Oct 8, 2021 · 2 comments
Open

Jest 测试相关配置 #36

ChelesteWang opened this issue Oct 8, 2021 · 2 comments

Comments

@ChelesteWang
Copy link
Owner

moduleNameMapper [object<string, string | array>]#

Default: null

从正则表达式到模块名或模块名数组的映射,允许在单个模块中删除资源,如图像或样式。
默认情况下,映射到别名的模块是不被mock的,不管automocking是否被启用。
如果您想使用文件路径,请使用字符串令牌来引用rootDir值。
此外,您可以使用编号的反向引用替换捕获的正则表达式组。

Example:

{
  "moduleNameMapper": {
    "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
    "^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
    "module_name_(.*)": "<rootDir>/substituted_module_$1.js",
    "assets/(.*)": [
      "<rootDir>/images/$1",
      "<rootDir>/photos/$1",
      "<rootDir>/recipes/$1"
    ]
  }
}

定义映射的顺序很重要。图案被一个一个地检查,直到一个适合。首先应该列出最具体的规则。对于模块名称数组也是如此。
注意:如果你提供的模块名没有边界^$可能会导致很难发现错误。例如,relay将替换所有包含relay的模块:relay, react-relay和graphql-relay都将指向你的存根。

@ChelesteWang
Copy link
Owner Author

ChelesteWang commented Oct 8, 2021

jest 报 SyntaxError: Unexpected token 'export' 错误

当项目中项目中导入第三方模块(node_modules)是esm时,会报SyntaxError: Unexpected token 'export'错误。
默认情况下,Jest 不会转换 node_modules,因为一般来说 node_modules 中的js是被转换为cjs兼容的。
所以要解决这个问题需要配置 jest,可以在package.json中进行配置

{
  "name": "test-demo",
  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!(package-name1|package-name2))"
    ]
  }
}

还有一点需要注意,transformIgnorePatterns 不适用于.babelrc,仅适用于babel.config.js。

@ChelesteWang
Copy link
Owner Author

transform

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant