我有一个功能组件,可以在设置的超时后导航到另一个组件。这是在useEffect函数中完成的。
Component
import React, {useEffect} from 'react'; import {View, Text} from 'react-native'; const Startup: React.FC<> = props => { useEffect(() => { setTimeout(() => { props.navigation.navigate('Signup_Signin'); }, 3000); }); return ( <View> <Text>Startup View</Text> </View> ); }; export default Startup;
这里是测试
import 'react-native'; import React from 'react'; import { create } from 'react-test-renderer'; import Startup from '../../../src/views/Startup'; // Note: test renderer must be required after react-native. const createTestProps = (props: Object) => ({ navigation: { navigate: jest.fn(), }, ...props, }); describe('<Startup />', () => { const StartupView = create(<Startup {...createTestProps()} />); test('Matches the snapshot', () => { expect(StartupView.toJSON()).toMatchSnapshot(); }); test('Navigation called with Signup_Signin', () => { jest.useFakeTimers(); jest.advanceTimersByTime(3000); expect(StartupView.root.props.navigation.navigate).toHaveBeenCalledWith( 'Signup_Signin', ); }); });
我首先测试该组件是否匹配其快照,并且快照没有问题。然后,我创建一个假计时器,并将其推进到与组件中设置的计时器相同的计时器。然后,我可以验证是否已经调用了导航道具。
笑话错误消息
●›使用Signup_Signin调用的导航
expect(jest.fn()).toHaveBeenCalledWith(...expected) Expected: "Signup_Signin" Number of calls: 0 25 | jest.useFakeTimers(); 26 | jest.advanceTimersByTime(3000); > 27 | expect(StartupView.root.props.navigation.navigate).toHaveBeenCalledWith( | ^ 28 | 'Signup_Signin', 29 | ); 30 | });
似乎该道具从未被调用。我已经检查了我的应用程序,并且导航已经完成。我猜问题出在我如何描述测试。
我有一个功能组件,可以在设置的超时后导航到另一个组件。这是在useEffect函数中完成的。组件导入React,{useEffect}来自“ react”;导入{查看,文本} ...
it
internal'允许您检查某个值是否等于我们的expected
。
useEffect
在渲染发生时不会被同步调用。在SSR中,根本不调用它。您是否通过放置useEffect
来验证测试中是否完全调用过console.log
?