首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法模拟API请求

无法模拟API请求
EN

Stack Overflow用户
提问于 2020-03-06 13:12:12
回答 1查看 1.4K关注 0票数 3

在我的玩笑-测试-模拟项目中设置TypeScript非常困难。我想知道是否有人能为我指明正确的方向?

我有一个像这样的函数:

retrieveData.ts

代码语言:javascript
复制
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中这样测试它

代码语言:javascript
复制
// 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';,则不会。使用第一个导入语句的问题是,它错误地使用了我的linter,它说没有定义fetch。如果我在fetch导入之前控制台日志,它将显示正确的模拟构造函数。我试过使用模拟程序的导入顺序,但它仍然存在相同的问题:

代码语言:javascript
复制
import fetchMock, {enableFetchMocks} from 'jest-fetch-mock'
import {retrieveData, generateExport} from '../src/fetch'
enableFetchMocks()

这显然是某种进口订单问题,但我不确定用Jest解决这个问题的正确方法。在eslint中向全局对象添加fetch是解决这个问题的适当解决方案吗?

EN

回答 1

Stack Overflow用户

发布于 2020-03-06 14:53:10

你能试试这段代码吗。

代码语言:javascript
复制
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' })
    })
  })
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60564794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档