开发者问题收集

Jest + react-navigation 无法定位路线/参数

2020-07-10
6257

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

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

TypeError: Cannot read property 'params' of undefined

我的组件看起来像

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/ ,但在包装组件时收到 警告:React.createElement:类型无效

我的测试看起来喜欢

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个回答

嘿,我刚刚自己解决了这个问题,这是我的解决方案

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}/>);
Sam
2020-11-07