我在一个react代码库中添加了类型记录支持,当应用程序正常工作时,jest测试在整个地方都失败了,显然没有认识到一些关于es6语法的东西。
我们为此使用了T-玩笑。下面是我得到的错误消息,在尝试处理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。我们跟着他们向它添加TypeScript支持的指令,它的工作就像一个魅力,除了这个玩笑的部分,他们没有涵盖。
发布于 2018-09-07 02:07:39
我最终发现了问题所在。原来它一直都在time的自述中。
自述文件中有一个题为在Javascript文件中使用ES2015+特性的章节。在这些情况下,您需要指示jest使用babel-jest作为.js文件的转换。
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest", // Adding this line solved the issue
"^.+\\.tsx?$": "ts-jest"
},
// ...
},发布于 2018-09-04 21:08:46
正如你找到的文件所说,ts-jest需要CommonJS模块,因此由于主tsconfig.json设置了"module": "es6",所以您需要为ts-jest创建一个单独的tsconfig.json文件,该文件扩展了主tsconfig.json并设置了"module": "commonjs"。
发布于 2021-11-13 04:38:30
对我来说,关键是认识到测试应该转换为太的类型记录,或者,在tsconfig.json中添加
我无法找到一个与保持js测试一起工作的配置,但是将测试转换为ts可以修复这个错误。
mv tests/stuff.test.js tests/stuff.test.ts
一般来说,ts-jest的好处是有能力进行ts测试,所以无论如何都是一件好事。
https://stackoverflow.com/questions/52173815
复制相似问题