简体   繁体   English

编写单元测试以检查应用程序是否在 react-native 中脱机

[英]Writing a unit test to check if the app is offline in react-native

I have the following component which displays a text on the app if the app is offline.如果应用程序离线,我有以下组件在应用程序上显示文本。

import React from 'react';

import { useNetInfo } from '@react-native-community/netinfo';

import { Label } from 'components/ui';

const OfflineNotice = () => {
  const netInfo = useNetInfo();

  if (netInfo.type !== 'unknown' && netInfo.isInternetReachable === false) {
    return <Label size={18} text='No Internet Connection' />;
  }

  return null;
};

export default OfflineNotice;

I want to write a unit test to this to check if this works properly.我想为此编写一个单元测试以检查它是否正常工作。 How can I do this?我怎样才能做到这一点? Im new to unit tests.我是单元测试的新手。 I don't understand how to mock this.我不明白如何嘲笑这个。

I use typescript and testing-library/react-native.我使用 typescript 和 testing-library/react-native。

UPATED: Why does this first test fail?更新:为什么第一次测试失败? It should NOT TO BE NULL.它不应该是 NULL。 But it fails.但它失败了。 The error is,错误是,

OfflineNotice component › test

expect(received).not.toBeNull()

Received: null

  15 | 
  16 |     const { queryByText } = render(<OfflineNotice />);
> 17 |     expect(queryByText(/no internet connection/i)).not.toBeNull();
     |                                                        ^
  18 |   });
  19 | 

  at Object.<anonymous> (src/components/offline-notice/offline-notice.test.tsx:17:56)

Cruising the react-native-netinfo github repo, troubleshooting section巡航react-native-netinfo github repo, 故障排除部分

You should then add the following to your Jest setup file to mock the NetInfo Native Module:然后,您应该将以下内容添加到您的 Jest 设置文件中以模拟 NetInfo 本机模块:

 import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js'; jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);

Their mock for testing is:他们的测试模拟是:

const defaultState = {
  type: 'cellular',
  isConnected: true,
  isInternetReachable: true,
  details: {
    isConnectionExpensive: true,
    cellularGeneration: '3g',
  },
};

const RNCNetInfoMock = {
  configure: jest.fn(),
  fetch: jest.fn(),
  addEventListener: jest.fn(),
  useNetInfo: jest.fn(),
};

RNCNetInfoMock.useNetInfo.mockResolvedValue(defaultState);

Given this I think you could craft your own mock resolved values in each unit test case:鉴于此,我认为您可以在每个单元测试用例中制作自己的模拟解析值:

import { useNetInfo } from '@react-native-community/netinfo';

jest.mock('@react-native-community/netinfo', () => {
  useNetInfo: jest.fn(),
});

...

// Happy path test, known type and internet unreachable
useNetInfo.mockResolvedValueOnce({
  type: 'test', // not 'unknown'
  isInternetReachable: false,
});
// assert render non-null
const { queryByText } = render(<OfflineNotice />);
expect(queryByText(/no internet connection/i)).not.toBeNull();

...

// Sad path test, known type and internet reachable
useNetInfo.mockResolvedValueOnce({
  type: 'test', // not 'unknown'
  isInternetReachable: true,
});
// assert render null
const { queryByText } = render(<OfflineNotice />);
expect(queryByText(/no internet connection/i)).toBeNull();

...

// Sad path test, unknown type and internet unreachable
useNetInfo.mockResolvedValueOnce({
  type: 'unknown',
  isInternetReachable: false,
});
// assert render null
const { queryByText } = render(<OfflineNotice />);
expect(queryByText(/no internet connection/i)).toBeNull();

...

// Sad path test, unknown type and internet reachable
useNetInfo.mockResolvedValueOnce({
  type: 'test', // not 'unknown'
  isInternetReachable: true,
});
// assert render null
const { queryByText } = render(<OfflineNotice />);
expect(queryByText(/no internet connection/i)).toBeNull();

React-Native-Testing-Library React-Native-Testing-Library

React-Testing-Library反应测试库

Now my tests are working.现在我的测试正在运行。 But it gives the unexpected outputs.但它给出了意想不到的输出。

COMPONENT:成分:

import React from 'react';

import { useNetInfo } from '@react-native-community/netinfo';

import { Label } from 'components/ui';
import strings from './offline-notice.strings';
import styles from './offline-notice.styles';

const OfflineNotice = ({ style, text }: IProps) => {
  const netInfo = useNetInfo();

  if (netInfo.type !== 'unknown' && netInfo.isInternetReachable === false) {
    return <Label size={18} style={[styles.label, style]} text={text} />;
  }

  return null;
};

OfflineNotice.defaultProps = {
  text: strings.NO_INTERNET_CONNECTION,
};

interface IProps {
  style?: Object;
  text?: string;
}

export default OfflineNotice;

TEST:测试:

import { render } from '@testing-library/react-native';
import React from 'react';

import { useNetInfo } from '@react-native-community/netinfo';

import OfflineNotice from './offline-notice.component';
import strings from './offline-notice.strings';

describe('OfflineNotice component', () => {
  it('should display the message if internet is not reachable', () => {
    useNetInfo.mockResolvedValueOnce({
      type: 'test',
      isInternetReachable: false,
    });

    const { getByText } = render(<OfflineNotice text={strings.NO_INTERNET_CONNECTION} />);
    expect(getByText(strings.NO_INTERNET_CONNECTION)).not.toBeNull();
  });

  it('should not display the message if internet is reachable', () => {
    useNetInfo.mockResolvedValueOnce({
      type: 'test',
      isInternetReachable: true,
    });

    const { getByText } = render(<OfflineNotice text={strings.NO_INTERNET_CONNECTION} />);
    expect(getByText(strings.NO_INTERNET_CONNECTION)).toBeNull();
  });
});

Jest.Setup.ts Jest.Setup.ts

import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js';

jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);

When running the test, following output is given.运行测试时,给出以下输出。 What am I doing wrong here?我在这里做错了什么?

在此处输入图片说明

As @Drew said, I set the configuration according by documentation , but I did a little difference in mock for testing.正如@Drew 所说,我根据文档设置了配置,但我在模拟测试中做了一些不同的工作。

For me, I did this and worked:对我来说,我这样做并工作:

jest.mock('@react-native-community/netinfo', () => ({
  ...jest.requireActual('@react-native-community/netinfo'),
  useNetInfo: () => ({
    isConnected: true,
  })
}));

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

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