javascriptreactjsunit-testingreact-testing

React Js API call Jest Test Case?


I am trying to write test cases for my API call function and I don't know where is the error that I could not run my test successfully here is the API call function Code and test Cases code.

export async function getUserTest() {
    fetch(config.apiUrl.myFleetAPI, {
        method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + 'GcGs5OF5TQ50sbjXRXDDtG8APTSa0s'
        }
    })
        .then((response) => {
            return response.json();
        })
        .catch((reject) => console.log(reject));
    
}

Test Case Code .

import React from 'react'; import { getUserTest } from '../Service/Dashboard/Dashboard';

global.fetch = jest.fn();
const mockAPICall = (option, data) => global.fetch.mockImplementation(() => Promise[option](data));

describe('Car Components component', () => {
    describe('when rendered', () => {
        it('should call a fetchData function', async () => {
            const testData = { current_user: 'Rahul Raj', name: 'Lafarge' };

            mockAPICall('resolve', testData);
            return getUserTest().then((data) => {
                expect(data).toEqual(testData);
            });
        });
    });
});

and here is what I am getting an error when I tried to run the Test Cases.

 Car Components component
    when rendered
      ✕ should call a fetchData function (5 ms)

  ● Car Components component › when rendered › should call a fetchData function

    expect(received).toEqual(expected) // deep equality

    Expected: {"current_user": "Rahul Raj", "name": "Lafarge"}
    Received: undefined

      65 |             mockAPICall('resolve', testData);
      66 |             return getUserTest().then((data) => {
    > 67 |                 expect(data).toEqual(testData);
         |                              ^
      68 |             });
      69 |         });
      70 |     });

      at src/Test/MainScreen.test.js:67:30

  console.log
    TypeError: response.json is not a function
        at /Users/rahulraj/Documents/Workproject/Vivafront/lafargeClone/src/Service/Dashboard/Dashboard.js:44:29
        at processTicksAndRejections (internal/process/task_queues.js:93:5)

Solution

  • There are two problems with your code:

    1. The resolved value of fetch function is Response which has a .json() method, you forgot to mock it.

    2. You forgot to return the promise like return fetch(/.../). This will cause the promise chain in the test case to not wait for the fetch promise to complete, which is why the return result is undefined

    E.g.

    api.js:

    const config = {
      apiUrl: {
        myFleetAPI: 'http://localhost:3000/api',
      },
    };
    export async function getUserTest() {
      return fetch(config.apiUrl.myFleetAPI, {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + 'GcGs5OF5TQ50sbjXRXDDtG8APTSa0s',
        },
      })
        .then((response) => {
          return response.json();
        })
        .catch((reject) => console.log(reject));
    }
    

    api.test.js:

    import { getUserTest } from './api';
    
    describe('68771600', () => {
      test('should pass', () => {
        const testData = { current_user: 'Rahul Raj', name: 'Lafarge' };
    
        const response = { json: jest.fn().mockResolvedValueOnce(testData) };
        global.fetch = jest.fn().mockResolvedValueOnce(response);
    
        return getUserTest().then((data) => {
          expect(data).toEqual(testData);
        });
      });
    });
    

    test result:

     PASS  examples/68771600/api.test.js (9.885 s)
      68771600
        ✓ should pass (3 ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |      80 |      100 |   66.67 |      80 |                   
     api.js   |      80 |      100 |   66.67 |      80 | 18                
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        10.794 s