React Native: Simulate offline device in Jest unit test

4.2k Views Asked by At

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

There are 1 best solutions below

8
On BEST ANSWER

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