1

I'm building a React Native app and I'm writing my unit tests using Jest.

(As you can see from this question,) I'm writing a function that checks if there is a network connection.

Here is the function (checkNetwork.ts):

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;

Now I want to mock this function when testing another function that makes API calls.

I created a folder called __mocks__ adjacent to checkNetwork.ts inside checkNetwork/ (see folder structure below). In it I created another file called checkNetwork.ts, too, which contains the mock and looks like this:

const checkNetwork = () => new Promise(resolve => resolve(true));

export default checkNetwork;

The function that uses this function makes a simple fetch request (postRequests.ts):

import checkNetwork from "../../core/checkNetwork/checkNetwork";

export const postRequestWithoutHeader = (fullUrlRoute: string, body: object) =>
  checkNetwork().then(() =>
    fetch(fullUrlRoute, {
      method: "POST",
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" }
    }).then(response =>
      response.json().then(json => {
        if (!response.ok) {
          return Promise.reject(json);
        }
        return json;
      })
    )
  );

The folder structure looks like this:

myreactnativeproject
  ├── app/
  │   ├── services/
  │   │   ├── utils/
  │   │   │    └── core/
  │   │   │        └── checkNetwork/
  │   │   │              └── checkNetwork.ts
  │   │   ├── serverRequests/
  │   │   │    └── POST/
  │   │   │        └── postRequests.ts
  │   .   .
  │   .   .
  │   .   .
  .
  .
  .

I then created another file called postRequests.test.ts within POST/ to write unit tests for postRequests.test.ts. I would now expect for Jest to automatically use the mock which returns true. But what is actually happening is that the test fails returning NO_NETWORK_CONNECTION. How can I get Jest to use the mock?

J. Hesters
  • 13,117
  • 31
  • 133
  • 249

1 Answers1

0

Here is the solution, folder structure doesn't matter, for keeping it simple, the folder structure like this:

.
├── __mocks__
│   └── checkNetwork.ts
├── checkNetwork.ts
├── errors.ts
├── postRequests.test.ts
└── postRequests.ts

checkNetwork.ts:

import NetInfo from '@react-native-community/netinfo';
import { NO_NETWORK_CONNECTION } from './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;

postRequests.ts:

import checkNetwork from './checkNetwork';
import fetch from 'node-fetch';

export const postRequestWithoutHeader = (fullUrlRoute: string, body: object) =>
  checkNetwork().then(() =>
    fetch(fullUrlRoute, {
      method: 'POST',
      body: JSON.stringify(body),
      headers: { 'Content-Type': 'application/json' }
    }).then(response =>
      response.json().then(json => {
        if (!response.ok) {
          return Promise.reject(json);
        }
        return json;
      })
    )
  );

Unit test:

postRequests.test.ts:

import { postRequestWithoutHeader } from './postRequests';
import fetch from 'node-fetch';

const { Response } = jest.requireActual('node-fetch');

jest.mock('./checkNetwork.ts');
jest.mock('node-fetch');

describe('postRequestWithoutHeader', () => {
  const mockedData = { data: 'mocked data' };
  const mockedJSONData = JSON.stringify(mockedData);
  const urlRoute = 'https://github.com/mrdulin';
  const body = {};

  it('should post request without header correctly', async () => {
    (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(new Response(mockedJSONData));
    const actualValue = await postRequestWithoutHeader(urlRoute, body);
    expect(actualValue).toEqual(mockedData);
    expect(fetch).toBeCalledWith(urlRoute, {
      method: 'POST',
      body: JSON.stringify(body),
      headers: { 'Content-Type': 'application/json' }
    });
  });

  it('should post request error', async () => {
    const mockedResponse = new Response(mockedJSONData, { status: 400 });
    (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(mockedResponse);
    await expect(postRequestWithoutHeader(urlRoute, body)).rejects.toEqual(mockedData);
    expect(fetch).toBeCalledWith(urlRoute, {
      method: 'POST',
      body: JSON.stringify(body),
      headers: { 'Content-Type': 'application/json' }
    });
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/52673113/postRequests.test.ts
  postRequestWithoutHeader
    ✓ should post request without header correctly (7ms)
    ✓ should post request error (1ms)

-----------------|----------|----------|----------|----------|-------------------|
File             |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files        |      100 |      100 |      100 |      100 |                   |
 postRequests.ts |      100 |      100 |      100 |      100 |                   |
-----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.996s, estimated 5s

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/52673113

Dependencies:

"@react-native-community/netinfo": "^4.2.1",
"react-native": "^0.60.5",

I am using the latest version react-native module, so the NetInfo module is deprecated. https://facebook.github.io/react-native/docs/netinfo.html

Lin Du
  • 88,126
  • 95
  • 281
  • 483