小编Śān*_*anu的帖子

使用 Jest 测试时如何用模拟替换 React 组件

在我正在从事的项目中,我真的很困惑,我找到的所有答案似乎都很简单,但它们对我不起作用。也许我不太明白模拟是什么,我真的需要一些指导。

\n\n

我正在测试一个父组件,该组件有一个子组件,该子组件使用 GraphQL 从数据库中获取一些数据。在测试父母时,我不关心孩子在做什么。我想用模拟组件(不从数据库获取数据的组件)替换子组件,这样我就可以只关注父组件。

\n\n

我想出了一个最简单的例子来展示我的情况。请注意,我正在使用 React Native 和 React Native 测试库。

\n\n

./src/ParentComponent.js

\n\n
import React from \'react\';\nimport { Text, View } from \'react-native\';\nimport ChildComponent from \'./ChildComponent\';\n\nconst ParentComponent = () => (\n  <View>\n    <Text>Hello World</Text>\n    <ChildComponent />\n  </View>\n);\n\nexport default ParentComponent;\n
Run Code Online (Sandbox Code Playgroud)\n\n

./src/ChildComponent.js

\n\n
import React from \'react\';\nimport { useQuery } from \'react-apollo\';\nimport { View, Text } from \'react-native\';\nimport gql from \'graphql-tag\';\n\nconst CURRENT_USER_QUERY = gql`\n  query {\n    currentUser {\n      username\n    }\n  }\n`;\n\nconst ChildComponent = () => {\n  const { …
Run Code Online (Sandbox Code Playgroud)

mocking reactjs jestjs react-native-testing-library

8
推荐指数
1
解决办法
6056
查看次数

如何使用 Jest 和 Native 测试库正确测试 React Native Modals

我很难理解如何测试我的模态组件。我正在使用React-native-modals包和@testing-library/react-native和 Jest。我的组件是一个模式,当 GraphQL 错误传递给它时会弹出。

./ErrorMessage.js

import React from 'react';
import PropTypes from 'prop-types';
import { Dimensions, Text } from 'react-native';
import Modal, { ModalContent, ScaleAnimation } from 'react-native-modals';
import { theme } from '../styles/theme.styles';

const ModalError = ({ error, onClose }) => {
  if (!error || !error.message) {
    return (
      <Modal visible={false}>
        <Text />
      </Modal>
    );
  }

  return (
    <Modal
      visible
      modalAnimation={
        new ScaleAnimation({
          initialValue: 0,
          useNativeDriver: true,
        })
      }
      onTouchOutside={onClose}
      swipeDirection={['up', 'down', 'left', 'right']}
      swipeThreshold={200} …
Run Code Online (Sandbox Code Playgroud)

reactjs react-native react-native-testing-library

6
推荐指数
1
解决办法
8880
查看次数