React Native:在 Jest 单元测试中模拟离线设备 [英] React Native: Simulate offline device in Jest unit test

查看:26
本文介绍了React Native:在 Jest 单元测试中模拟离线设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 React Native 应用程序,我正在使用 Jest 对我的代码进行单元测试.

I'm writing a React Native app and I'm using Jest to unit test my code.

我编写了一个函数来检查是否有互联网连接.我知道想写它的单元测试.我被卡住了,因为我不知道如何在单元测试中模拟设备的连接状态.

I've written a function than checks if there is an internet connection. I know want to write it's unit tests. I'm stuck, because I can't figure out how to mock the connection state of the device in a unit test.

您将如何在单元测试中模拟设备离线或在线?

How would you simulate that the device is offline or online in a unit test?

这是函数:

import { NetInfo } from "react-native";
import { NO_NETWORK_CONNECTION } from "../../../../config/constants/errors";

const checkNetwork = (): Promise<boolean | string> =>
  new Promise((resolve, reject) => {
    NetInfo.isConnected
      .fetch()
      .then(isConnected => (isConnected ? resolve(true) : reject(NO_NETWORK_CONNECTION)))
      .catch(() => reject(NO_NETWORK_CONNECTION));
  });

export default checkNetwork;

我想在我的测试中测试它,看看它是否正确解析为 true 如果设备已连接,如果请求失败则拒绝字符串.为此,我需要在我的单元测试中模拟设备连接.

And I would like to test it in my test to see if it correctly resolves with true if the device is connected and rejects with the string, if the request fails. For that I need to simulate the devices connection in my unit tests.

推荐答案

这很简单,只需像这样模拟 NetInfo :

This is pretty simple, just mock the NetInfo like so:

import {
    NetInfo
} from "react-native";
import checkNetwork from "...";
import {
    NO_NETWORK_CONNECTION
} from "...";

jest.mock('react-native', () => ({
    NetInfo: {
        isConnected: {
            fetch: jest.fn()
        }
    }
}))

test('test offline', async () => {
    NetInfo.isConnected.fetch.mockResolvedValueOnce(false)
    expect(await checkNetwork()).toBe(NO_NETWORK_CONNECTION)
})

test('test online', async () => {
    NetInfo.isConnected.fetch.mockResolvedValueOnce(true)
    expect(await checkNetwork()).toBe(true)
})

这篇关于React Native:在 Jest 单元测试中模拟离线设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆