React ~ Testing ~ Mocking API - rohit120582sharma/Documentation GitHub Wiki

Introduction

Fetch is the new way to do HTTP requests in the browser, and it can be used in other environments such as React Native. Jest Fetch Mock allows you to easily mock your fetch calls and return the response you need to fake the HTTP requests.

References



Installation and Setup

npm install --save-dev jest-fetch-mock
// test/setupTests.js
global.fetch = require('jest-fetch-mock');
// jest.config.js
module.exports = {
    automock: false,
    setupTestFrameworkScriptFile: "<rootDir>src/test/setupTests.js",
}


API

fetch.mockResponse(bodyOrFunction, init): fetch - Mock all fetch calls

fetch.mockResponseOnce(bodyOrFunction, init): fetch - Mock each fetch call independently

fetch.mockReject(errorOrFunction): fetch - Mock all fetch calls, letting them fail directly

fetch.mockRejectOnce(errorOrFunction): fetch - Let the next fetch call fail directly

fetch.resetMocks(): Clear previously set mocks so they do not bleed into other mocks

fetch.mock: The mock state for your fetch calls. Make assertions on the arguments given to fetch when called by the functions you are testing.



Example

//api.js
export function APIRequest(who) {
    if (who === 'google') {
        return fetch('https://google.com').then(res => res.json())
    } else {
        return 'no argument provided'
    }
}
//api.test.js
import { APIRequest } from './api'

describe('testing api', () => {
    beforeEach(() => {
        fetch.resetMocks();
    });
    it('calls google and returns data to me', () => {
        fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));

        //assert on the response
        APIRequest('google').then(res => {
        expect(res.data).toEqual('12345');
        });

        //assert on the times called and arguments given to fetch
        expect(fetch.mock.calls.length).toEqual(1);
        expect(fetch.mock.calls[0][0]).toEqual('https://google.com');
    });
});
⚠️ **GitHub.com Fallback** ⚠️