繁体   English   中英

如何用 jest 重写测试?

[英]How to rewrite test with jest?

嗨,我进行了简单的快照测试,但我需要使用 redux 工具包从 API 保存数据,之后它总是失败。

DashboardScreen.tsx

const DashboardScreen = () => {
// added block of code
  const dispatch = useDispatch();

  const { data: userData } = useGetUserDataQuery();
  useEffect(() => {
    if (userData) dispatch(setCurrentUser(userData));
  }, [dispatch, userData]);
// end of added block of code

  return (
    <View style={styles.container}>
      <View style={styles.containerWidth}>
        <Image
          style={styles.logo}
          source={require('../../assets/images/KonektoSmart-logo.png')}
        />
      </View>
    </View>
  );
};

和测试DashboardScreen-test-tsx

test('renders correctly', () => {
  const tree = create(<DashboardScreen />).toJSON();
  expect(tree).toMatchSnapshot();
});

● 测试套件无法运行——但我尝试了一些下并不起作用。

[@RNC/AsyncStorage]: NativeModule: AsyncStorage is null.

To fix this issue try these steps:

  • Run `react-native link @react-native-async-storage/async-storage` in the project root.

  • Rebuild and restart the app.

  • Run the packager with `--reset-cache` flag.

  • If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app.

  • If this happens while testing with Jest, check out docs how to integrate AsyncStorage with it: https://react-native-async-storage.github.io/async-storage/docs/advanced/jest

为了解决这个问题,我需要使用Provider 对我来说,文档不清楚这样做。 完整代码:

import React from 'react';
import { create } from 'react-test-renderer';
import DashboardScreen from '../DashboardScreen';
import { Provider } from 'react-redux';
import store from '../../redux/store';

test('renders correctly', async () => {
  const tree = create(<Provider store={store}><DashboardScreen /></Provider>).toJSON();
  expect(tree).toMatchSnapshot();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM