我想看看启动屏幕在一定时间后是否可以很好地导航到另一个屏幕。但是我不知道如何配置测试代码。
我模拟了导航功能,并将其作为道具放置在屏幕组件中,并且该导航功能应在异步等待功能之后执行。
AuthLoading.tsx
import React, { useState } from 'react';
import { Asset } from 'expo-asset';
import { SplashScreen } from 'expo';
import { NavigationScreenProp, NavigationState } from 'react-navigation';
import styled from 'styled-components/native';
import { IMG_GIF_SPLASH } from '../../utils/Images';
interface IProps {
navigation: NavigationScreenProp<NavigationState>;
}
const SPLASH_SHOW_TIME = 1500;
const Container = styled.SafeAreaView`
flex: 1;
background-color: white;
align-items: center;
justify-content: center;
`;
const StyledSplashImage = styled.Image`
width: 200;
height: 47;
margin-bottom: 50%;
`;
const StyledText = styled.Text`
color: #cdd3d3;
position: absolute;
bottom: 50;
`;
export default (props: IProps) => {
const [areResourcesReady, setResourcesReady] = useState(false);
const [isAppReady, setAppReady] = useState(false);
const cacheResourcesAsync = async () => {
Asset.fromModule(IMG_GIF_SPLASH).downloadAsync();
setResourcesReady(true);
};
React.useEffect(() => {
if (!isAppReady) {
SplashScreen.preventAutoHide();
cacheResourcesAsync();
return;
}
// if non-authorized user
props.navigation.navigate('AuthStackNavigator');
// if authorized user
// props.navigation.navigate('MainStackNavigator');
}, []);
if (!isAppReady && areResourcesReady) {
return (
<Container>
<StyledSplashImage
source={IMG_GIF_SPLASH}
resizeMode='contain'
onLoadEnd={() => {
setTimeout(() => {
setAppReady(true);
}, SPLASH_SHOW_TIME);
SplashScreen.hide(); // Image is fully presented, instruct SplashScreen to hide
}}
/>
<StyledText>ⓒ Whatssub Studio</StyledText>
</Container>
);
}
return (<Container />);
};
AuthLoaing.test.tsx
import 'react-native';
import * as React from 'react';
import AuthLoading from '../AuthLoading';
import renderer from 'react-test-renderer';
import { render, RenderResult } from '@testing-library/react-native';
const createTestProps = (props: Object) => ({
navigation: {
navigate: jest.fn(),
},
...props,
});
let props: any;
let component: React.ReactElement;
let testing: RenderResult;
describe('[AuthLoading] Interaction', () => {
beforeAll(() => {
props = createTestProps({});
component = <AuthLoading {...props} />;
testing = render(component);
});
it('should navigate to another screen', () => {
jest.runAllTimers();
expect(props.navigation.navigate).toBeCalledTimes(1);
});
});
我希望props.navigation.navigate在测试代码中被调用1次