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)
这是解决方案,我node-fetch使用模拟模块jest.mock()。
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\nRun Code Online (Sandbox Code Playgroud)\n\n单元测试:
\n\nimport { 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\nRun 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\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
7234 次 |
| 最近记录: |