Reactjs 使用Jest在useEffect钩子中测试超时后的导航(react navigation)调用
我有一个功能组件,可以在设置的超时后导航到另一个组件。这是在useEffect函数中实现的 组件Reactjs 使用Jest在useEffect钩子中测试超时后的导航(react navigation)调用,reactjs,react-native,jestjs,react-navigation,react-hooks,Reactjs,React Native,Jestjs,React Navigation,React Hooks,我有一个功能组件,可以在设置的超时后导航到另一个组件。这是在useEffect函数中实现的 组件 import React, {useEffect} from 'react'; import {View, Text} from 'react-native'; const Startup: React.FC<> = props => { useEffect(() => { setTimeout(() => { props.navigation
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',
);
});
});
似乎从未调用该道具。我已经通过我的应用程序进行了检查,导航已经完成。我猜问题来自于我如何描述测试。
it
internal'允许您检查某个值是否是我们所期望的值
但是,移动屏幕的函数没有要检查的值,因为没有结果返回值
试验可按如下方式进行:
it('Signup\u sign'调用导航,()=>{
开玩笑。使用faketimers();
setTimeout(()=>{props.navigation.navigate('Signup_sign');},3000);
jest.runAllTimers();
});
//或
它('通过注册调用导航',(完成)=>{
设置超时(()=>{
道具.导航.导航('Signup_Signin');
完成();
}, 3000);
});
发生渲染时,不会同步调用
useffect
。在SSR中,根本不调用它。您是否通过放置控制台.log
,验证了测试中是否调用了useffect
我建议使用类似的方法进行测试,它可以自动处理这样的事情
同样值得重新思考的测试。这似乎是在测试实现细节。我不明白为什么我必须在测试中手动执行导航功能,因为我想验证它是否在组件挂钩中自动执行。
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 | });