How to unit test API calls with mocked fetch() in react-native with Jest

How to unit test API calls with mocked fetch() in react-native with Jest

To unit test API calls with mocked fetch() in React Native using Jest, you can mock the fetch() function and verify that it behaves as expected. Here's a step-by-step guide on how to achieve this:

Example Component and API Call

Let's assume you have a React Native component that makes an API call using fetch():

// api.js
export const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
};

Unit Test Setup

1. Mocking fetch() with Jest

First, create a mock for fetch() that simulates a successful and failed API call:

// __mocks__/fetch.js

const fetchMock = jest.fn();

fetchMock.mockImplementation((url) => {
  if (url === 'https://api.example.com/data') {
    return Promise.resolve({
      ok: true,
      json: () => Promise.resolve({ message: 'Data fetched successfully' }),
    });
  } else {
    return Promise.resolve({
      ok: false,
      status: 404,
      statusText: 'Not Found',
    });
  }
});

export default fetchMock;

2. Writing Unit Test Using Jest

Now, write a Jest test to verify the behavior of fetchData():

// __tests__/api.test.js

import { fetchData } from '../api';
import fetchMock from 'fetch'; // Import the mocked fetch

describe('fetchData', () => {
  beforeEach(() => {
    fetchMock.mockClear(); // Clear mock call count before each test
  });

  it('fetches successfully', async () => {
    const data = await fetchData();
    expect(fetchMock).toHaveBeenCalledTimes(1);
    expect(data).toEqual({ message: 'Data fetched successfully' });
  });

  it('handles fetch error', async () => {
    fetchMock.mockImplementationOnce(() =>
      Promise.resolve({
        ok: false,
        status: 500,
        statusText: 'Internal Server Error',
      })
    );

    await expect(fetchData()).rejects.toThrow('Network response was not ok');
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });
});

Explanation:

  • Mocking fetch(): In the mock (fetch.js), fetchMock is defined using jest.fn() to create a Jest mock function. Depending on the URL parameter passed to fetch(), it returns different responses (simulating success or failure).

  • Unit Test (api.test.js):

    • Success Test: Tests that fetchData() successfully fetches data from the mocked API endpoint (https://api.example.com/data) and returns the expected data.
    • Error Handling Test: Tests that fetchData() correctly handles a failed API call and throws an error when fetch() returns a non-successful response.
  • beforeEach(): Clears the mock call count before each test to ensure clean test conditions.

Running Tests

Ensure that Jest is configured to find your tests correctly (jest.config.js or in your package.json), and then run the tests using:

jest

Notes:

  • Mocking Behavior: Adjust the mocked responses in fetch.js (fetchMock.mockImplementation()) to match the specific scenarios you want to test (e.g., different HTTP status codes, error responses).

  • Async/Await: Use async/await in tests to handle asynchronous fetch() calls and assertions.

  • Integration: Ensure that the mocked responses (fetchMock) closely match the actual behavior of the API endpoints you're testing against.

By following these steps, you can effectively unit test API calls in React Native using Jest with mocked fetch() functions. This approach helps ensure that your components behave correctly under different API response scenarios without making actual network requests during testing. Adjust the tests and mocks according to your specific API integration and testing requirements.

Examples

  1. Mocking fetch() for API testing in React Native with Jest

    • Description: How to mock the fetch() function to unit test API calls in React Native using Jest.
    • Code:
      jest.mock('node-fetch');
      
      import fetch from 'node-fetch';
      
      describe('API calls testing', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches data from an API', async () => {
          fetch.mockResolvedValueOnce({ json: () => ({ data: 'mocked data' }) });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data).toEqual({ data: 'mocked data' });
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This example sets up a Jest test to mock the fetch() function using jest.mock() and fetch.mockResolvedValueOnce() to simulate an API call and test the response.
  2. Unit testing React Native API calls with fetch() mocking

    • Description: Example of unit testing API calls in a React Native application by mocking fetch() with Jest.
    • Code:
      jest.mock('node-fetch');
      import fetch from 'node-fetch';
      
      describe('API tests', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches data successfully', async () => {
          fetch.mockResolvedValueOnce({
            json: () => Promise.resolve({ id: 1, name: 'Test Data' }),
          });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data.id).toBe(1);
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This test sets up a mocked fetch() call using jest.mock() and fetch.mockResolvedValueOnce() to simulate fetching data from an API endpoint and verifies the response.
  3. Mocking API requests in React Native using Jest

    • Description: Demonstrates how to mock API requests in a React Native component using Jest and fetch().
    • Code:
      jest.mock('node-fetch');
      import fetch from 'node-fetch';
      
      describe('API testing', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches and handles data from API', async () => {
          fetch.mockResolvedValueOnce({ json: () => Promise.resolve({ message: 'Mocked data' }) });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data.message).toBe('Mocked data');
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This test uses Jest to mock fetch() and simulate an API call in a React Native environment, ensuring proper handling of the fetched data.
  4. React Native Jest unit test for API calls with fetch()

    • Description: How to write a Jest unit test for API calls in React Native using mocked fetch().
    • Code:
      jest.mock('node-fetch');
      import fetch from 'node-fetch';
      
      describe('API tests', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches data from API endpoint', async () => {
          fetch.mockResolvedValueOnce({ json: () => Promise.resolve({ status: 'success' }) });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data.status).toBe('success');
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This test verifies the behavior of fetching data from an API endpoint using fetch() in React Native, with Jest mocking for controlled unit testing.
  5. Testing API calls in React Native with Jest and mocked fetch()

    • Description: Example of testing API calls in React Native using Jest with fetch() mocked.
    • Code:
      jest.mock('node-fetch');
      import fetch from 'node-fetch';
      
      describe('API tests', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches data from API', async () => {
          fetch.mockResolvedValueOnce({ json: () => Promise.resolve({ result: 'mocked data' }) });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data.result).toBe('mocked data');
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This Jest test mocks the fetch() function to simulate fetching data from an API endpoint in a React Native application and validates the response.
  6. Mocking fetch() in Jest for React Native API testing

    • Description: How to use Jest to mock the fetch() function for testing API calls in React Native.
    • Code:
      jest.mock('node-fetch');
      import fetch from 'node-fetch';
      
      describe('API testing', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches data from API endpoint', async () => {
          fetch.mockResolvedValueOnce({ json: () => Promise.resolve({ status: 'ok' }) });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data.status).toBe('ok');
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This test demonstrates mocking fetch() using Jest to test fetching data from an API endpoint in a React Native environment.
  7. Unit testing API calls in React Native with Jest

    • Description: Example of unit testing API calls in React Native using Jest with a mocked fetch() function.
    • Code:
      jest.mock('node-fetch');
      import fetch from 'node-fetch';
      
      describe('API tests', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches data from API', async () => {
          fetch.mockResolvedValueOnce({ json: () => Promise.resolve({ data: 'mocked response' }) });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data.data).toBe('mocked response');
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This test showcases how to use Jest to mock fetch() and test fetching data from an API in a React Native application.
  8. Mocking fetch() for API testing in React Native

    • Description: How to mock the fetch() function to test API calls in a React Native application using Jest.
    • Code:
      jest.mock('node-fetch');
      import fetch from 'node-fetch';
      
      describe('API tests', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches data from API endpoint', async () => {
          fetch.mockResolvedValueOnce({ json: () => Promise.resolve({ result: 'mocked data' }) });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data.result).toBe('mocked data');
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This Jest test mocks fetch() to simulate an API call in a React Native environment and verifies the returned data.
  9. Testing React Native API calls with Jest and mocked fetch()

    • Description: Example of using Jest to test API calls in a React Native app by mocking fetch().
    • Code:
      jest.mock('node-fetch');
      import fetch from 'node-fetch';
      
      describe('API tests', () => {
        beforeEach(() => {
          fetch.mockClear();
        });
      
        it('fetches data from API endpoint', async () => {
          fetch.mockResolvedValueOnce({ json: () => Promise.resolve({ message: 'mocked data' }) });
      
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
      
          expect(data.message).toBe('mocked data');
          expect(fetch).toHaveBeenCalledTimes(1);
          expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
        });
      });
      
    • Explanation: This test demonstrates how to mock fetch() in Jest to test API calls in a React Native application and validate the returned data.

More Tags

uppercase doctest n-ary-tree jquery-ui-sortable owl-carousel-2 android-hardware auto-versioning angular-builder encodable ppi

More Programming Questions

More Stoichiometry Calculators

More Date and Time Calculators

More Fitness Calculators

More Weather Calculators