muscalu-c
2/1/2019 - 3:19 PM

mocking simple api

import fetchData  from './Api';

describe('API Caller', () => {
    it('should call YesNo API', () => {
        const fetchSpy = jest.spyOn(global, 'fetch')
            .mockImplementation(() => Promise.resolve({
                json: () => {},
            }));

        return fetchData()
            .then(() => {
                expect(fetchSpy).toHaveBeenCalledWith('https://yesno.wtf/api/');
            })
    });

    it('should return YesNo response in JSON format', () => {
        jest.spyOn(global, 'fetch')
            .mockImplementation(() => Promise.resolve({
                json: () => ({ foo: 'bar' }),
            }));

        return fetchData()
            .then(response => {
                expect(response).toEqual({ foo: 'bar' });
            });
    });

    afterEach(() => {
        jest.resetAllMocks();
    });
});

//Api.js
export default () => fetch(`https://yesno.wtf/api/`)
    .then(response => response.json());

//__mocks__/Api.js
export default () => Promise.resolve({
    answer: 'no',
    forced: false,
    image: 'https://yesno.wtf/assets/no/0-b6d3e555af2c09094def76cf2fbddf46.gif'
});