I want to mock the fetch function with additional blob extraction using jest.fn().mockimplementation() and without using fetch-mock or jest-fetch-mock
fetch(url)
.then((response) => response.blob)
.then((data) => imageHandler(data))
I want to mock the fetch function with additional blob extraction using jest.fn().mockimplementation() and without using fetch-mock or jest-fetch-mock
fetch(url)
.then((response) => response.blob)
.then((data) => imageHandler(data))
Share
Improve this question
asked Aug 13, 2019 at 4:49
user3507230user3507230
832 silver badges10 bronze badges
2 Answers
Reset to default 5Here is the solution, I mock node-fetch
module using jest.mock()
.
import fetch from 'node-fetch';
function fetchBlobImage() {
const url = '';
return fetch(url)
.then(response => response.blob)
.then(blob => processImage(blob));
}
function processImage(blob) {
return JSON.stringify(blob);
}
export { fetchBlobImage };
Unit tests:
import { fetchBlobImage } from './';
jest.mock('node-fetch', () => {
const context = {
then: jest.fn().mockImplementationOnce(() => {
const blob = {};
const response = { blob };
return Promise.resolve(response);
})
};
return jest.fn(() => context);
});
describe('node-fetch', () => {
it('should be mock correctly', async () => {
const actualValue = await fetchBlobImage();
expect(actualValue).toBe(JSON.stringify({ blob: {} }));
});
});
Test results:
PASS src/mock-module/node-fetch/index.spec.ts
node-fetch
✓ should be mock correctly (5ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.25s, estimated 3s
Here is a solution that worked for me since I was not using 'node-fetch' and writing test in Typescript.
describe('my fetch test', () => {
beforeAll(() => {
global.fetch = jest.fn().mockImplementation(() =>
Promise.resolve({
json: () => Promise.resolve({ /* your expected mock response */ }),
blob: () => Promise.resolve({})
})
) as jest.Mock;
});
afterAll(() => jest.clearAllMocks());
// your tests
});