使用jest遇到es6 import语法报错的问题解决

使用jest进行对npm包测试时报错:

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

在该文章查到解决方案 :https://www.cnblogs.com/xueyoucd/p/10495922.html

配置完后发现jest引用的文件使用import是没报错了,但是jest内引用的包在node_modules里使用了es6语法,仍然报错。

此时问题变成:

node_modules 使用es6 import而transform未识别到。

最终查到原因是:

jest默认会对node_modules包内的不进行转换,所以要到配置修改这个字段

transformIgnorePatterns [array<string>]

Default: ["/node_modules/"]

改掉。

(比如项目只忽略当前目录的node_modules,改成"transformIgnorePatterns": ["<rootDir>/node_modules/"])

官方说明:https://jestjs.io/docs/en/configuration#transformignorepatterns-arraystring

到此该问题终于得以解决!

推荐阅读 更多精彩内容