如何使用jest测试React原生Typescript应用程序组件?
我一直在尝试用jest测试我的React原生Typescript组件,但很长一段时间都没有成功。我找到了很多例子/答案(包括:,,等等),但没有一个有用。 将设置更改为示例项目(带有进一步链接)或另一个示例项目()中所示的设置不起作用 通过某些设置,我可以运行简单的测试,但如果我尝试导入组件,则会出现错误:如何使用jest测试React原生Typescript应用程序组件?,typescript,react-native,ts-jest,Typescript,React Native,Ts Jest,我一直在尝试用jest测试我的React原生Typescript组件,但很长一段时间都没有成功。我找到了很多例子/答案(包括:,,等等),但没有一个有用。 将设置更改为示例项目(带有进一步链接)或另一个示例项目()中所示的设置不起作用 通过某些设置,我可以运行简单的测试,但如果我尝试导入组件,则会出现错误: ● Test suite failed to run Jest encountered an unexpected token This usually means that you
● Test suite failed to run
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.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/XXX/node_modules/react-native-iphone-x-helper/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Dimensions, Platform, StatusBar } from 'react-native';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/react-native-paper/lib/commonjs/components/BottomNavigation.tsx:13:1)
}
package.json“jest”
有人能给我指出一个有效的示例吗?找到了一个有效的示例设置: 我确实遗漏了jest.setup.js文件和行
setupFilesAfterEnv: ['./jest.setup.js'],
在jest.config.js文件中
"jest": {
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
"\\.(ts|tsx)$": "ts-jest"
},
"globals": {
"ts-jest": {
"tsConfig": "tsconfig.jest.json"
}
},
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
{"compilerOptions": {
"target": "es6",
"module": "commonjs",
"allowJs": true,
"jsx": "react-native",
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}, "include": [
"src"
]}
setupFilesAfterEnv: ['./jest.setup.js'],