React Native: Simulate offline device in Jest unit test

ぃ、小莉子 提交于 2019-12-01 22:36:53

问题


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?

Edit:

Here is the function:

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;

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.


回答1:


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)
})


来源:https://stackoverflow.com/questions/52633466/react-native-simulate-offline-device-in-jest-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!