我试图用react导航为一个应用程序编写一个测试,并且我遇到了正确读取的路径和参数的问题。
我得到了一个错误
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(),
};
});我不确定我是否对组件进行了错误的包装,或者是否遗漏了其他内容。
任何想法或帮助都将不胜感激。
谢谢。
发布于 2020-11-07 02:20:42
嘿,我自己解决了这个问题,这是我的解决办法
变化
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}/>);https://stackoverflow.com/questions/62825431
复制相似问题