TypeScript中Jest模拟react-native-modal的JSX语法错误排查
问题原因及解决办法
核心原因
出现Operator '>' cannot be applied to types 'View' and '{ children: React.ReactNode; }'错误,是因为你在模拟react-native-modal时,错误地将View组件以普通函数调用的方式拼接参数,而非使用标准JSX语法。TypeScript会把这种写法识别为类型比较操作,而非创建React元素,从而触发类型不匹配报错。
解决办法
方法1:使用独立模拟文件(推荐)
在项目根目录创建__mocks__/react-native-modal.tsx文件,按照标准JSX语法编写模拟组件,同时对齐原组件的类型定义:
import React from 'react'; import { View, ViewProps } from 'react-native'; // 模拟Modal组件,继承View的Props并添加Modal核心属性 const Modal = ({ children, visible = true, ...props }: ViewProps & { visible?: boolean }) => { // 可根据测试需求控制渲染逻辑,比如仅当visible为true时渲染子组件 return visible ? <View {...props}>{children}</View> : null; }; export default Modal;
方法2:在Jest配置/测试文件中直接模拟
如果需要在Jest配置或测试文件内直接模拟,确保使用React.createElement创建合法JSX元素:
// 在jest.config.js中配置模块映射 module.exports = { // 其他Jest配置项... moduleNameMapper: { 'react-native-modal': '<rootDir>/__mocks__/react-native-modal.tsx', }, }; // 或者在单个测试文件顶部直接模拟 jest.mock('react-native-modal', () => { const React = require('react'); const { View } = require('react-native'); return ({ children, ...props }) => React.createElement(View, props, children); });
关键注意事项
- 禁止使用
View({ children })这类写法,必须用<View>{children}</View>或React.createElement创建JSX元素。 - 模拟组件的Props类型要与原组件对齐,至少包含
children和常用属性(如visible),避免额外类型报错。 - 确保
tsconfig.json中已引入React Native相关类型,比如compilerOptions.types包含@types/react-native、@types/jest。
内容的提问来源于stack exchange,提问作者Mike S.
相关产品推荐
相关产品推荐

