在调试或发布模式构建期间不会发生警告,而是在测试App.js时发生:
App.js
import React from 'react';
import { View, AppRegistry } from 'react-native';
import { gestureHandlerRootHOC } from 'react-native-gesture-handler';
import { LocalizationProvider } from 'library/localization';
import NavigationService from 'library/NavigationService';
import AppNavigator from 'library/AppNavigator';
const App = () => {
return (
<>
<LocalizationProvider>
<AppNavigator
ref={(navigatorRef) => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
</LocalizationProvider>
</>
);
};
AppRegistry.registerComponent(appName, () => gestureHandlerRootHOC(App));
export default App;
如果我从AppNavigator中删除引用,则不会出现错误。
AppNavigator.js
const guestUserNavigation = createStackNavigator(
{
Login: {
screen: LoginScreen
},
Logout: {
screen: LogoutActivity
}
},
{
headerMode: 'none',
initialRouteName: 'Login'
}
);
const userNavigation = createStackNavigator(
{
Home: {
screen: HomeScreen
}
},
{
headerMode: 'none',
initialRouteName: 'Home'
}
);
const App = createSwitchNavigator({
loader: {
screen: AuthLoadingScreen
},
Auth: {
screen: guestUserNavigation
},
App: {
screen: userNavigation
}
});
const AppNavigator = createAppContainer(App, {
initialRouteName: 'loader'
});
export default AppNavigator;
App.test.js
import React from 'react';
import { render } from 'react-native-testing-library';
import App from './App';
describe('App', () => {
it('should render the App', () => {
const result = render(<App />).toJSON();
expect(result).toMatchSnapshot();
});
});
嘲笑 /react-navigation.js
jest.mock('react-navigation', () => ({
createAppContainer: jest
.fn()
.mockReturnValue(function NavigationContainer(props) {
return null;
}),
createSwitchNavigator: jest.fn(),
NavigationActions: {
navigate: jest.fn().mockImplementation((x) => x)
}
}));
现在测试通过并带有以下警告,这困扰了我,我似乎无法使其正常工作:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `App`.
in NavigationContainer (at App.js:29)
in LocalizationProvider (at App.js:28)
in App (at App.test.js:7)
使用forwardRef可以工作,但应用程序无法呈现。
答案 0 :(得分:1)
AppNavigator
不应返回null
,因为这会使模拟无法测试App
。
为了接收引用,AppNavigator
应该是类或forwardRef
的组成部分。 createAppContainer
参数可以选择在元素层次结构中表示,以便可以通过快照进行测试:
...
createAppContainer: jest.fn((Comp, options) => React.forwardRef((props, ref) => {
return <div data-testid="AppContainer" ref={ref}>
<div data-testid="createAppContainer component">
{Comp.name}
</div>
<div data-testid="createAppContainer options">
{JSON.stringify(options)}
</div>
{children}
</div>;
})),
...