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

查看:178
本文介绍了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天全站免登陆