Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Simulate offline device in Jest unit test

Tags:

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.

like image 744
J. Hesters Avatar asked Oct 03 '18 18:10

J. Hesters


1 Answers

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)
})
like image 168
Herman Starikov Avatar answered Oct 03 '22 20:10

Herman Starikov