我正在向 React 代码库添加 typescript 支持,虽然应用程序运行正常,但 jest 测试到处都失败了,显然无法识别 es6 语法。
我们正在使用 ts-jest为了这。下面是我在尝试处理 jest 的测试设置文件时立即收到的错误消息。
FAIL src/data/reducers/reducers.test.js
● Test suite failed to run
/Users/ernesto/code/app/react/setupTests.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import './polyfills';
^^^^^^^^^^^^^
SyntaxError: Unexpected string
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
它无法识别一个简单的 import './polyfills'
,说引用的字符串是意外的。
这些是我的设置:
package.json 中的 jest 配置
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/app/react/setupTests.js",
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
},
tsconfig.json
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"module": "es6",
"moduleResolution": "node",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"target": "es5",
"jsx": "react",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"skipDefaultLibCheck": true,
"strictPropertyInitialization": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"noErrorTruncation": true
},
"exclude": ["app/assets","node_modules", "vendor", "public"],
"compileOnSave": false
}
.babelrc
{
"presets": [
[
"env",
{
"modules": false,
"targets": {
"browsers": "> 1%",
"uglify": true
},
"useBuiltIns": true
}
],
"react",
"es2015"
],
"plugins": [
"syntax-dynamic-import",
"transform-object-rest-spread",
[
"transform-class-properties",
{
"spec": true
}
]
]
}
如果相关,这是在 Rails 应用程序中使用的 React 代码库,我们使用 rails/webpacker为此。我们关注了their instructions to add TypeScript support to it ,它就像一个魅力,除了这个他们没有涵盖的 Jest 部分。
最佳答案
我终于找到问题所在了。事实证明它一直存在于 ts-jest 的自述文件中。
自述文件中有一个标题为 Using ES2015+ features in Javascript files 的部分.在这些情况下,您需要指示 jest 使用 babel-jest
作为 .js 文件的转换。
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest", // Adding this line solved the issue
"^.+\\.tsx?$": "ts-jest"
},
// ...
},
关于typescript - ts-jest 不识别 es6 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52173815/