I’m trying to create a Jest mock for react-native-modal in a React Native project using TypeScript. However, TypeScript doesn’t recognize the return statement as valid JSX. It throws the following error:
Operator '>' cannot be applied to types 'View' and '{ children: React.ReactNode; }'.
I’ve tried two approaches to resolve the issue, but both result in the same error. Here are the approaches:
Standalone mock file:
import React from 'react';
import { View, ViewProps } from 'react-native';
interface ModalProps extends ViewProps {
visible: boolean;
children: React.ReactNode;
}
const Modal: React.FC<ModalProps> = ({ children, visible, ...props }) => {
if (!visible) {
return null;
}
return <View {...props}>{children}</View>;
};
export default Modal;
In the Jest setup file:
jest.mock('react-native-modal', () => {
const React = require('react');
const View = require('react-native').View;
return ({children, visible, ...props}) => {
if (!visible) {
return null;
}
return <View {...props}>{children}</View>;
};
});
I’ve verified that the react-native and react imports are correct, and other JSX components work fine. Code assists and TypeScript error messages aren’t helping much to pinpoint what’s wrong with the syntax.
Any ideas on what might be causing this error and how to resolve it? Is there something specific to JSX in TypeScript or Jest mocks that I’m missing?
I think typeScript id struggling to correctly infer the types for your JSX components in mock environment. You wrote a mock for the react-native-modal
component but typeScript didn't recognise JSX in your return statement correctly due to which there was an error saying it can't apply certain operations to the types.
for typescript to understand the expected types, we have to explicitly define the types React.FC<ModalProps>
to tell typeScript that this is a functional component with the props defined.
I have updated youre mock file to add appropriate types:
jest.mock('react-native-modal', () => {
const React = require('react');
const View = require('react-native').View;
interface ModalProps extends ViewProps {
visible: boolean;
children: React.ReactNode;
}
const Modal: React.FC<ModalProps> = ({ children, visible, ...props }) => {
if (!visible) {
return null;
}
return <View {...props}>{children}</View>;
};
return Modal;
})
also make sure that youre tsconfig file is configured for jsx
{
"compilerOptions": {
"jsx": "react"
.
.
}
Let me know if this works!