开玩笑地嘲笑获取响应 blob 的 fetch() 函数

use*_*230 2 javascript fetch ecmascript-6 reactjs jestjs

我想使用 jest.fn().mockimplementation() 来模拟 fetch 函数,并使用 jest.fn().mockimplementation() 进行额外的 blob 提取,而不使用 fetch-mock 或 jest-fetch-mock

fetch(url)
.then((response) => response.blob)
.then((data) => imageHandler(data))
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 5

这是解决方案,我node-fetch使用模拟模块jest.mock()

\n\n
import fetch from \'node-fetch\';\n\nfunction fetchBlobImage() {\n  const url = \'\';\n  return fetch(url)\n    .then(response => response.blob)\n    .then(blob => processImage(blob));\n}\n\nfunction processImage(blob) {\n  return JSON.stringify(blob);\n}\n\nexport { fetchBlobImage };\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

单元测试:

\n\n
import { fetchBlobImage } from \'./\';\n\njest.mock(\'node-fetch\', () => {\n  const context = {\n    then: jest.fn().mockImplementationOnce(() => {\n      const blob = {};\n      const response = { blob };\n      return Promise.resolve(response);\n    })\n  };\n  return jest.fn(() => context);\n});\n\ndescribe(\'node-fetch\', () => {\n  it(\'should be mock correctly\', async () => {\n    const actualValue = await fetchBlobImage();\n    expect(actualValue).toBe(JSON.stringify({ blob: {} }));\n  });\n});\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

检测结果:

\n\n
 PASS  src/mock-module/node-fetch/index.spec.ts\n  node-fetch\n    \xe2\x9c\x93 should be mock correctly (5ms)\n\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        2.25s, estimated 3s\n
Run Code Online (Sandbox Code Playgroud)\n