jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
882 stars 116 forks source link

Unable to mock fetch response #153

Closed JamesIves closed 4 years ago

JamesIves commented 4 years ago

Having a really hard time setting this library up 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

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?

JamesIves commented 4 years ago

Just a small update: Using import 'cross-fetch/polyfill'; instead of import fetch from 'cross-fetch'; makes it so my tests will pass, however it's erroring my linter now saying that fetch is undefined.