开玩笑+反应导航未找到路线/参数

时间:2020-07-10 00:00:51

标签: javascript react-native jestjs react-navigation react-native-testing-library

我正在尝试使用react-navigation为应用程序编写测试,并且遇到了正确读取路线和参数的问题。

我遇到了一个错误

TypeError:无法读取未定义的属性“ params”

const [leadId] = useState(route.params.leadId);

我的组件看起来像

export default function AComponent() {
  const route = useRoute();
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const [leadId] = useState(route.params.leadId);
}

我尝试遵循https://callstack.github.io/react-native-testing-library/docs/react-navigation/,但是在包装组件时收到了Warning: React.createElement: type is invalid

我的测试看起来像

import React from 'react';
import { Provider } from 'react-redux';
import { NavigationContainer } from '@react-navigation/native';
import { render, fireEvent, cleanup } from 'react-native-testing-library';
import configureMockStore from 'redux-mock-store';

import AComponent from 'components/contact/AComponent';

const mockStore = configureMockStore([]);

describe('<AComponent />', () => {
  let getByTestId, store;

  beforeEach(() => {
    store = mockStore({});

    ({ getByTestId } = render(
      <Provider store={store}>
        <AComponent />
      </Provider>
    ));
  });
});

我的模拟是

jest.mock('@react-navigation/native', () => {
  return {
    useNavigation: () => ({ goBack: jest.fn() }),
    useRoute: jest.fn(),
  };
});

我不确定是否包装组件不正确,或者是否缺少其他物品。

任何想法或帮助将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:1)

嘿,我自己解决了这个,这是我的解决方法

更改

jest.mock('@react-navigation/native', () => {
  return {
    useNavigation: () => ({ goBack: jest.fn() }),
    useRoute: jest.fn(),
  };
});

收件人

jest.mock('@react-navigation/native', () => ({
  ...jest.requireActual('@react-navigation/native'),
  useNavigation: () => ({ goBack: jest.fn() }),
  useRoute: () => ({
    params: {
      <yourParamName>: '<paramValue>',
      <yourParamName2>: '<paramValue2>',
      etc...
    }
  }),
}));

在我的情况下,我将此代码块放入setup.ts文件中,然后在package.json内的jest配置中指出了这一点。

示例

"setupFiles": [
  "./node_modules/react-native-gesture-handler/jestSetup.js",
  "./jest/setup.ts"
]

然后在测试本身中

const navigation = { navigate: jest.fn() };
const { getByTestId, getByText, queryByTestId } = render(<App navigation={navigation}/>);
相关问题