测试Reaction Native app:How to Fix:Navigation.setOptions is Not a Function?测试、app、How、Native

2023-09-04 02:25:49 作者:沒你我怎麼過

测试如下:


describe('<HomeScreen />', () => {
  it('Renders correctly', () => {

// const setOptions = jest.fn(); // 1
// const setOptions = (navigation: any, route: any) => { } // 2
//   const setOptions = (props: HomeProps) => { } // 3
//  const setOptions = (options: Partial<NativeStackNavigationOptions>) => void // 4

    render(
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <HomeScreen navigation={{ setOptions: setOptions }} route={undefined} />
        </PersistGate>
      </Provider>,
    );
  });
});

我已经尝试了here和here提供的解决方案,但它们对我不起作用。

HiNative下载 HiNative app安卓版下载 v3.2.2 跑跑车安卓网

我认为问题在于我使用的是TypeScrip和Reaction导航V6,因为:

const setOptions = jest.fn(); 我收到:

Type '{ setOptions: jest.Mock<any, any>; }' is not assignable to type 'NativeStackNavigationProp<RootStackParamList, "Home">'.

NativeStackNavigationProp<RootStackParamList, "Home">是我的组件类型。

是这个:export type HomeProps = NativeStackScreenProps<RootStackParamList, 'Home'>;

稍后我将其导入为HomeProps

const setOptions = (navigation: any, route: any) => { }

我得到:

Type '(navigation: any, route: any) => void' is not assignable to type '(options: Partial<NativeStackNavigationOptions>) => void'.

const setOptions = (props: HomeProps) => { }

我得到:

Type '(props: HomeProps) => void' is not assignable to type '(options: Partial<NativeStackNavigationOptions>) => void'.

const setOptions = (options: Partial<NativeStackNavigationOptions>) => void (@队长-约塞里安的建议)

我得到:

Type '{ setOptions: (options: Partial<NativeStackNavigationOptions>) => any; }' is not assignable to type 'NativeStackNavigationProp<RootStackParamList, "Home">'.

我如何解决此问题?

推荐答案

考虑以下示例:

import React, { FC, useEffect } from "react";
import { View } from "react-native";
import "react-native";
import { render } from "@testing-library/react-native";
import { NativeStackScreenProps, NativeStackNavigationProp } from "@react-navigation/native-stack";

type RootStackParamList = {
  App: undefined;
};

export type AppProps = NativeStackScreenProps<RootStackParamList, "App">;

const App: FC<AppProps> = ({ navigation }) => {
  useEffect(() => {
    navigation.setOptions({
      headerRight: () => <View>hello</View>,
      gestureEnabled: false
    });
  });

  return <View>Hello</View>;
};

export default App;


const setOptions = (options: NativeStackNavigationProp<RootStackParamList, "App">) =>
  void (
    // 4

    render(
      <App navigation={options} route={{ key: 'hello', name: "App", }} />
    )
  );

Playground

我们需要对options使用NativeStackNavigationProp<RootStackParamList, "App">类型