【问题标题】:Jest mocking fetch() function that get the blob of the response开玩笑地模拟获取响应的 blob 的 fetch() 函数
【发布时间】:2019-12-19 15:06:17
【问题描述】:
我想通过 使用 jest.fn().mockimplementation() 和 不使用 fetch-mock 或 jest-fetch-mock 来模拟 fetch 函数
fetch(url)
.then((response) => response.blob)
.then((data) => imageHandler(data))
【问题讨论】:
标签:
javascript
reactjs
ecmascript-6
jestjs
fetch
【解决方案1】:
这是解决方案,我使用jest.mock() 模拟node-fetch 模块。
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 };
单元测试:
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: {} }));
});
});
测试结果:
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