I'm trying to implement a partially mocked WebView for testing in React Native. I have tried to setup a spy on the WebView component only overriding the injectedJavaScript prop. I would have assumed this works:
import WebView, * as RNWebView from 'react-native-webview';
// keep all props from the WebView componen, but override the injectedJavaScript prop
jest
.spyOn(RNWebView, 'WebView')
.mockImplementation(
(props: IOSWebViewProps & AndroidWebViewProps, context: any) => {
return (
<WebView
{...props}
injectedJavaScript={`window.ReactNativeWebView.postMessage("CUSTOM_MESSAGE")`}
/>
);
},
);
But I get the type error:
Argument of type '(props: IOSWebViewProps & AndroidWebViewProps, context: any) => JSX.Element' is not assignable to parameter of type '(props: IOSWebViewProps & AndroidWebViewProps, context: any) => WebView<unknown>'.
Type 'ReactElement<any, any>' is missing the following properties from type 'WebView<unknown>': goBack, goForward, reload, stopLoading, and 9 more.ts(2345)
I don't get it. How is the <WebView> I am returning being recognized only as type ReactElement<any, any>. Shouldn't <WebView>'s type quite literally be WebView? Really lost here, not sure why TypeScript is complaining. If I add as any to the end of the return statement, TypeScript is satisfied:
jest
.spyOn(RNWebView, 'WebView')
.mockImplementation(
(props: IOSWebViewProps & AndroidWebViewProps, context: any) => {
return (
<WebView
{...props}
injectedJavaScript={`window.ReactNativeWebView.postMessage("CUSTOM_MESSAGE")`}
/>
) as any;
},
);
But this is a hack and I want to know why my mock types are not being understood by TypeScript.