首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何使用Jest和本机测试库正确测试反应本机模型

如何使用Jest和本机测试库正确测试反应本机模型
EN

Stack Overflow用户
提问于 2020-04-13 19:23:09
回答 3查看 5.6K关注 0票数 5

我很难理解如何测试我的模态组件。我正在使用反应-本机情态包和Jest附带的@测试-库/反应-本机。我的组件是一个在传递GraphQL错误时弹出的模式。

./ErrorMessage.js

代码语言:javascript
代码运行次数:0
运行
复制
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}
      onSwipeOut={onClose}
      modalStyle={modalStyle}
      overlayOpacity={0.7}
    >
      <ModalContent>
        <Text testID="graphql-error">{error.message}</Text>
      </ModalContent>
    </Modal>
  );
};

ModalError.defaultProps = {
  error: {},
};

ModalError.propTypes = {
  error: PropTypes.object,
  onClose: PropTypes.func.isRequired,
};

export default ModalError;

const window = Dimensions.get('window');

const modalStyle = {
  backgroundColor: theme.lightRed,
  borderLeftWidth: 5,
  borderLeftColor: theme.red,
  width: window.width / 1.12,
};

到目前为止,我的测试相当简单。我只想确定它是在渲染模态。我不太清楚这里有什么需要嘲弄的东西,也不知道该怎么做。

./__tests__/ErrorMessage.test.js

代码语言:javascript
代码运行次数:0
运行
复制
import React from 'react';
import { MockedProvider } from '@apollo/react-testing';
import { GraphQLError } from 'graphql';
import { render } from '@testing-library/react-native';
import Error from '../ErrorMessage';

jest.mock('react-native-modals', () => 'react-native-modals');

const error = new GraphQLError('This is a test error message.');
const handleOnCloseError = jest.fn();

describe('<ErrorMessage>', () => {
  it('should render an ErrorMessage modal component', () => {
    const { container } = render(
      <MockedProvider>
        <Error error={error} onClose={handleOnCloseError} />
      </MockedProvider>
    );
    expect(container).toMatchSnapshot();
  });
});

我所犯的错误是..。

代码语言:javascript
代码运行次数:0
运行
复制
TypeError: _reactNativeModals.ScaleAnimation is not a constructor

      18 |       visible
      19 |       modalAnimation={
    > 20 |         new ScaleAnimation({
         |         ^
      21 |           initialValue: 0,
      22 |           useNativeDriver: true,
      23 |         })

快照只是打印..。

./__tests__/__snapshots__/ErrorMessage.test.js.snap

代码语言:javascript
代码运行次数:0
运行
复制
// Jest Snapshot v1, 

exports[`<ErrorMessage> should render an ErrorMessage modal component 1`] = `
<View
  collapsable={true}
  pointerEvents="box-none"
  style={
    Object {
      "flex": 1,
    }
  }
/>
`;

如何克服这个错误并创建一个正确的快照?

EN

回答 3

Stack Overflow用户

发布于 2021-04-16 10:54:19

您可以使用这个-> https://github.com/testing-library/jest-native

代码语言:javascript
代码运行次数:0
运行
复制
In react native component,
...
<Modal
        testID="test-modal"
        deviceWidth={deviceWidth}
        deviceHeight={deviceHeight}
        isVisible={isModalVisible}.  // isModalVisible = useState(true or false)
        onBackdropPress={toggleModal}
        backdropOpacity={0.5}
 >
...

In test component,
...
const test = getByTestId("test-modal");
expect(test).toHaveProp("visible", true);   // test success ! 
...
票数 1
EN

Stack Overflow用户

发布于 2022-01-06 17:50:41

代码语言:javascript
代码运行次数:0
运行
复制
// components/Example/index.tsx
import React, { useState } from 'react';
import { Pressable, Text } from 'react-native';
import Modal from 'react-native-modal';

const Example: React.FC = () => {
  const [isPrivacyPolicyVisible, setIsPrivacyPolicyVisible] = useState(false);

  return (
    <>
      <Pressable onPress={() => setIsPrivacyPolicyVisible(true)}>
        <Text>Privacy Policy</Text>
      </Pressable>

      <Modal
        accessibilityLabel="privacy-policy-modal"
        isVisible={isPrivacyPolicyVisible}>
        <Text>Content</Text>
      </Modal>
    </>
  );
};

export default Example;
代码语言:javascript
代码运行次数:0
运行
复制
// components/Example/index.test.tsx
import React from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react-native';

import { Example } from 'components';

describe('Example Component', () => {
  it('should render privacy policy.', async () => {
    // Arrange
    const { queryByText, queryByA11yLabel } = render(<Example />);

    const button = queryByText(/privacy policy/i);
    const modal = queryByA11yLabel('privacy-policy-modal');

    // Act and Assert
    expect(button).toBeTruthy();
    expect(modal).toBeTruthy();
    expect(modal.props).toMatchObject({
      visible: false,
    });
  });

  it('should show privacy policy modal.', async () => {
    // Arrange
    const { queryByText, queryByA11yLabel } = render(<Example />);

    const button = queryByText(/privacy policy/i);
    const modal = queryByA11yLabel('privacy-policy-modal');

    // Act
    await waitFor(() => {
      fireEvent.press(button);
    });

    // Assert
    expect(modal.props).toMatchObject({
      visible: true,
    });
  });
});
票数 1
EN

Stack Overflow用户

发布于 2020-09-16 16:20:55

当您执行jest.mock('react-native-modals', () => 'react-native-modals');时,您将整个库替换为字符串“react本机-modals”,因此当您在组件中使用它时,它会失败。您需要从模拟函数返回一个完全模拟的实现(jest.mock的第二个参数)。这也是可能的,自动嘲弄可能对您有用,这将通过简单的执行:jest.mock('react-native-modals');

下面是jest.mock()的停靠库,并给出了使用它的各种方法的一些示例:https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61195196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档