gpt4 book ai didi

reactjs - 在 react native + typescript 应用程序上运行 jest 时出错(Jest 遇到意外 token )

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:41 24 4
gpt4 key购买 nike

似乎每个人和他们的母亲都遇到了这个问题的变体。我从所有 SO 问题和 GH 票证中尝试过的一切都没有任何效果。

它实际上应该很简单,因为我的项目几乎是一个新的准系统项目。然而,我仍然无法弄清楚我的生活出了什么问题。

当我运行 jest 时:

/Desktop/Dropbox/Programming/iphone-app/fe/App.spec.tsx:11
const tree = react_test_renderer_1.default.create(<App_1.default />).toJSON();
^

SyntaxError: Unexpected token <

我的配置文件:

// jest.config.js

module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};

-

// tsconfig.json

{
"compilerOptions": {
"allowJs": false,
"allowSyntheticDefaultImports": true,
"noFallthroughCasesInSwitch": true,
"experimentalDecorators": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react-native",
"lib": [
"es6"
],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext"
},
"exclude": [
"node_modules"
]
}

-

// babel.config.js

module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
};
};

编辑#1

需要说明的是,我已经尝试在 jest 配置文件中使用 react-native 预设,但没有成功(同样的错误):

// jest.config.js

module.exports = {
preset: 'react-native',
transform: {
'^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
'^.+\\.tsx?$': 'ts-jest'
},
globals: {
'ts-jest': {
tsConfig: 'tsconfig.json'
}
},
testEnvironment: 'node',
};

最佳答案

它适用于这个配置文件:

const { defaults } = require('jest-config');

module.exports = {
preset: 'react-native',
transform: {
'^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
'^.+\\.tsx?$': 'ts-jest'
},
moduleFileExtensions: [
'tsx',
...defaults.moduleFileExtensions
],
};

我需要添加

...
moduleFileExtensions: [
'tsx',
...defaults.moduleFileExtensions
],
...

否则 import App from './App';在我的测试中会解析为其他文件。通过添加 tsx作为 moduleFileExtensions 中的最高优先级选项,应用会解析正确的文件。

还有 jsx tsconfig.json 中的编译器选项需要设置为"jsx": "react" .我不确定为什么我不能将它设置为 react-native然而,但目前一切似乎都有效。

编辑

'^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js'在新版本的 react-native 中不需要. Keeping it may also cause a problem.

关于reactjs - 在 react native + typescript 应用程序上运行 jest 时出错(Jest 遇到意外 token ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com