最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jest mocking fetch() function that get the blob of the response - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 5

Here 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
});
发布评论

评论列表(0)

  1. 暂无评论