typescript - 无法模拟 API 请求

标签 typescript jestjs jest-fetch-mock

很难设置 jest-test-mock在我的 TypeScript 项目中。我想知道是否有人可以指出正确的方向?

我有一个看起来像这样的函数:

retrieveData.ts

import fetch from 'cross-fetch'; 

export async function retrieveData({
  endpoint,
  configuration,
  auth
}: dataInterface): Promise<object> {
  try {
    console.log('Fetching the requested data... 📦')

    const settings = configuration
      ? JSON.parse(render(configuration || '', auth))
      : {}

    if (settings.body) {
      // Ensures the body is stringified in the case of a post request being made.
      settings.body = JSON.stringify(settings.body)
    }

    const response = await fetch(endpoint, settings)
    return await response.json()
  } catch (error) {
    throw new Error(`There was an error fetching from the API: ${error}`)
  }
}

我正在 fetch.test.ts

中这样测试它
// Enable the mocks
import { enableFetchMocks } from 'jest-fetch-mock'
enableFetchMocks()
import fetchMock from 'jest-fetch-mock';

import {retrieveData, generateExport} from '../src/fetch'

describe('fetch', () => {
  describe('retrieveData', () => {
    it('should return some data', async () => {
      fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' }))
      const data = await retrieveData({
        endpoint: 'https://example.com'
      })

      expect(data).toEqual({ data: '12345' })
    })
  })
})

我遇到的问题是这个库似乎没有接管对fetch 的调用。将完全限定的 URL 放入我的函数中将导致返回实际数据。我希望它检索 data: '12345' 对象。我哪里出错了?

更新:

以下模式在导入 import 'cross-fetch/polyfill'; 时有效,但如果我使用 import fetch from 'cross-fetch'; 则无效。使用第一个 import 语句的问题是它使我的 linter 出错,说 fetch 未定义。如果我在提取导入之前控制台日志,它会显示正确的模拟构造函数。我试过玩弄模拟的导入顺序,但它仍然有同样的问题:

import fetchMock, {enableFetchMocks} from 'jest-fetch-mock'
import {retrieveData, generateExport} from '../src/fetch'
enableFetchMocks()

这显然是某种导入顺序问题,但我不确定使用 Jest 解决此问题的正确方法。将 fetch 添加到 eslint 中的全局对象是否是一个合适的解决方案?

最佳答案

请你试试这段代码。

describe('retrieveData', () => {
  it('should return some data', () => {
    fetchMock.mockResponseOnce(JSON.stringify({ data: '12345' }))
    retrieveData({
      endpoint: 'https://example.com'
    }).then(res => {
       expect(res).toEqual({ data: '12345' })
    })
  })
})

关于typescript - 无法模拟 API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60564794/

相关文章:

node.js - Jest 测试失败时如何打印请求和响应?

javascript - 返回值后多次调用 ngrx 效果

typescript - 尝试使用空 ts 项目初始化 webpack 时出错

javascript - 模态中的单击事件 - 测试

javascript - 在自定义钩子(Hook)中测试 fetch.catch

unit-testing - 如何对不存在的外部依赖进行开 Jest

debugging - Chrome Typescript 调试引用错误 'this'

javascript - 你如何获得裁判的姓名?

javascript - 用 Jest 测试回调函数