Sunday, July 3, 2022

Mock node-fetch with JEST

Recently I tried my hands on Jest - the popular JavaScript Testing Library. In my application we were using node-fetch to make API calls. I used Jest to mock and test this API calls. Here in this blog I will explain on how to mock node-fetch with Jest. 

Following is my function to call the GET API. 

fetch_get.js

const fetch = require('node-fetch');

module.exports = async () => {

    return await fetch('http://YOUR_GET_URL').then(res => res.json());

};

Now to test this create a test file with name test.fetch_get.js

Step 1: First import the function.

const fetch_get = require('../fetch_get');


Step 2 : Mock the node-fetch with Jest

const fetch = require('node-fetch');
jest.mock('node-fetch', ()=>jest.fn())

Step 3: Create Mock response

const mockedRes = {
  "success": true,
  "data": [
    {
        id: 1,
        text: 'Test Data 1'
    },
    {
        id: 1,
        text: 'Test Data 2'
    }
  ]
};

Step 4: Add Test 

describe("Test get fetch", () => {
    let data;
    it('It should return the data', () => {
      const response = Promise.resolve({
            ok: true,
            status: 200,
            json: () => {
                return mockedRes;
            },
        });
        fetch.mockImplementation(()=> response)
        data = await fetch_get();
        expect(data).toEqual(mockedRes);
    });
});

In above code we have created a rest and mocked the response to return our response when we call .json() method for response. Then we are simply comparing the response. This is a very simple test. Here in stead of comparing data, you may have other tests like checking length of data or checking specific data etc.

Step 5: Run Test

Run the test with npm test or npm run test and you will see the following result.

Test get fetch
    ✓ It should return the data (17 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.313 s, estimated 1 s

Hope this helps you.

No comments:

Post a Comment