You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:22:35