React测试中Renderer JSON无Children属性的Typescript报错问题
解决方案
该问题属于静态类型检查异常,测试可正常运行说明运行时配置无误,仅IDE加载类型声明时出错,可按以下步骤排查解决:
- 首先检查是否存在类型包版本冲突:
jest-expo已经内置了Jest相关类型声明,如果你单独安装了@types/jest,很可能出现版本不匹配导致的类型报错,执行以下命令卸载单独的Jest类型包即可:npm uninstall @types/jest
用yarn的用户执行:yarn remove @types/jest - 检查
tsconfig.json配置,确保compilerOptions.types字段包含测试相关类型,且include字段覆盖了所有测试文件:{ "compilerOptions": { // 其他配置保持不变 "types": ["react", "react-native", "jest", "@types/react-test-renderer"] }, "include": [ "src/**/*", "**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx" ] } - 确认根目录下Jest配置文件(
jest.config.js/jest.config.ts)的预设值为jest-expo,示例配置如下:module.exports = { preset: 'jest-expo', transformIgnorePatterns: [ 'node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)' ] } - 最后重启VS Code的TypeScript语言服务即可生效:按下
Ctrl+Shift+P(Mac系统为Cmd+Shift+P),搜索并执行「TypeScript: Restart TS Server」。
以上操作执行完成后,IDE的类型报错会自动消失,不需要修改你的测试代码逻辑。
内容的提问来源于stack exchange,提问作者Msw Tm
相关产品推荐
相关产品推荐

