简体   繁体   English

如何修复 TypeError:navigation.setOptions 不是 function

[英]How to fix TypeError: navigation.setOptions is not a function

I'm trying to implement react native test library with jest to my app.我正在尝试用我的应用程序开玩笑地实现本机测试库。

For now I have a problem with the navigation on my component.现在我的组件导航有问题。

When I'm running the test, I've got an error:当我运行测试时,我遇到了一个错误:

TypeError: navigation.setOptions is not a function

Here is my component:这是我的组件:

const initialState: StateTypes = {
  toShowAsGridLayout: false,
  isLoadingMoreContacts: false
};

export const Main: FC<Props> = ({ navigation }) => {
  const dispatch = useDispatch();
  const { data } = useSelector((state: RootState) => state.appReducer);

  const [state, setState] = useState<StateTypes>(initialState);

  useLayoutEffect(() => {
    navigation.setOptions({
      title: state.isLoadingMoreContacts ? strings.LOADING : strings.ALL_CONTACTS + ' - ' + data.length,
      headerRight: () => (
        <TouchableOpacity style={styles.changeLayoutButton} onPress={changeLayout}>
          <Text style={styles.changeLayoutText}>{state.toShowAsGridLayout ? strings.LIST : strings.GRID}</Text>
        </TouchableOpacity>
      )
    });
  }, [state.isLoadingMoreContacts, state.toShowAsGridLayout])

  return (
    <View style={styles.container}>
      {renderLayout()}
    </View>
  );
};

Here is a router:这是一个路由器:

const SplashStack = createStackNavigator();
const MainStack = createStackNavigator();

export const RootNavigator = () => {
  const { isDataLoading } = useSelector((state: RootState) => state.appReducer);

  return (
    isDataLoading
      ? <SplashStack.Navigator>
        <SplashStack.Screen name={'SplashStack'} component={Splash} />
      </SplashStack.Navigator>
      : <MainStack.Navigator>
        <MainStack.Screen name={'Main'} component={Main} />
        <MainStack.Screen name={'ContactDetails'} component={ContactDetails} />
      </MainStack.Navigator>
  );
};

And a test itself:还有一个测试本身:

import React from 'react';

import { render } from '@testing-library/react-native';
import { Main } from '../Main';
import * as redux from 'react-redux';
import strings from '../../constants/strings';
import mocks from '../../mocks';

describe('dispatch mock', () => {
  it('should dispatch mock', () => {
    const useDispatchSpy = jest.spyOn(redux, 'useDispatch');
    const useSelectorSpy = jest.spyOn(redux, 'useSelector');
    const mockDispatchFn = jest.fn();
    useDispatchSpy.mockReturnValue(mockDispatchFn);
    useSelectorSpy.mockReturnValue({ data: mocks });

    const { getByText } = render(<Main navigation={({})} />);
    getByText(strings.ALL_CONTACTS);
  });
});

How can i fix this error?我该如何解决这个错误? What should I pass to navigation props in line:我应该将什么传递给导航道具:

const { getByText } = render(<Main navigation={({})} />);

You need to pass object with setOptions method.您需要使用setOptions方法传递对象。

const { getByText } = render(<Main navigation={
  {
    setOptions: (props: { title: string, headerRight: React.FC }) => void
  }
} />);

This answer might be relevant 这个答案可能是相关的

For my purpose solution was very easy, I just added ?.出于我的目的,解决方案非常简单,我只是添加了?. at the end of setOptionssetOptions结束时

useLayoutEffect(() => {
    navigation.setOptions?.({ // <--- CHANGED HERE 

      title: state.isLoadingMoreContacts ? strings.LOADING : strings.ALL_CONTACTS + ' - ' + data.length,
      headerRight: () => (
        <TouchableOpacity style={styles.changeLayoutButton} onPress={changeLayout}>
          <Text style={styles.changeLayoutText}>{state.toShowAsGridLayout ? strings.LIST : strings.GRID}</Text>
        </TouchableOpacity>
      )
    });
  }, [state.isLoadingMoreContacts, state.toShowAsGridLayout])

I am also face the same issue.我也面临同样的问题。 With below code changes I have resolved my issue.通过以下代码更改,我解决了我的问题。

For more info please check this answer有关更多信息,请查看此答案

    const createTestProps = (props: Object) => ({
          navigation: {
            navigate: jest.fn(),
            setOptions: jest.fn()
          },
          ...props
        });
    const props = createTestProps({});    
    const { toJSON } = render(<MainScreen {...props} />); 

在此处输入图像描述

You have to mock the properties and function that your are using in your screen has to be mocked like above.您必须模拟您在屏幕中使用的属性和 function 必须像上面一样模拟。 For more info please check this answer有关更多信息,请查看此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 navigation.setOptions() 在 React Native(expo 环境)中不起作用 - navigation.setOptions() doesn't work in React Native (expo environment) 如何修复TypeError:registerUser不是函数 - How to fix TypeError: registerUser is not a function 如何修复:&#39;TypeError:fetchProducts不是函数&#39; - How to fix: 'TypeError: fetchProducts is not a function' 如何修复 Uncaught TypeError: mapster is not a function? - How to fix Uncaught TypeError: mapster is not a function? 如何修复&#39;TypeError:(images || [])。forEach不是一个函数&#39; - How to fix 'TypeError: (images || []).forEach is not a function' 如何修复“TypeError:System.config 不是函数” - How to fix ''TypeError: System.config is not a function' 如何修复 TypeError 不是函数(用 Jest 测试 promise) - How to fix TypeError is not a function (testing promises with Jest) 如何修复 ReactTable 的“TypeError: resolveData(...).map is not a function” - How to fix 'TypeError: resolveData(...).map is not a function' for ReactTable 如何修复 React 中的“TypeError:moment is not a function”? - How to fix 'TypeError: moment is not a function' in React? 如何解决React Native中的导航问题(TypeError:undefined不是一个对象(评估&#39;_this.props.navigation)) - How to fix navigation problem in React Native (TypeError: undefined is not an object (evaluating '_this.props.navigation)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM