Unable to mock API request

喜夏-厌秋 提交于 2021-01-28 00:40:08

问题


Having a really hard time setting up jest-test-mock in in my TypeScript project. I was wondering if someone could point me in the right direction?

I've got a function that looks like this:

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}`)
  }
}

And I'm testing it like this in 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' })
    })
  })
})

The problem I'm having is that this library doesn't seem to take over the call to fetch. Putting a fully qualified URL into my function will result in actual data getting returned. I expect it to retrieve the data: '12345' object. Where am I going wrong here?

Update:

The following pattern works when importing import 'cross-fetch/polyfill'; but if I use import fetch from 'cross-fetch'; it does not. The problem with using the first import statement is that it errors my linter saying that fetch is not defined. If I console log before the fetch import it shows the correct mock constructor. I've tried playing around with the import order of the mocks but it still has the same problem:

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

It's clearly some sort of import order issue but I'm not sure the right way to solve this with Jest. Is adding a fetch to the global object in eslint an appropriate solution for this?


回答1:


Can you try this code, please.

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' })
    })
  })
})


来源:https://stackoverflow.com/questions/60564794/unable-to-mock-api-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!