jefflau / jest-fetch-mock

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

TypeError: Cannot redefine property: default #163

Closed JamesIves closed 4 years ago

JamesIves commented 4 years ago

I have a Jest unit test that uses jest-mock to mock an API response, it also mocks some function calls from a third party library. An example of the tests look like the following, the function it's testing makes a very basic fetch request using the crosss-fetch/polyfill library and then runs exportVariable.

import {exportVariable, setFailed} from '@actions/core'
import fetchMock, {enableFetchMocks} from 'jest-fetch-mock'
import run from '../src/lib'
enableFetchMocks()

const originalAction = JSON.stringify(action)

jest.mock('@actions/core', () => ({
  info: jest.fn(),
  setFailed: jest.fn(),
  getInput: jest.fn(),
  exportVariable: jest.fn()
}))

describe('lib', () => {
  afterEach(() => {
    Object.assign(action, JSON.parse(originalAction))
  })

  it('should run through the commands', async () => {
    fetchMock.mockResponseOnce(JSON.stringify({data: '12345'}))
    Object.assign(action, {
      endpoint: 'https://google.com'
    })
    await run(action)

    expect(exportVariable).toBeCalled()
  })
}

The error I'm getting is as follows:

  ● Test suite failed to run

    TypeError: Cannot redefine property: default
        at Function.defineProperty (<anonymous>)

       8 | const originalAction = JSON.stringify(action)
       9 | 
    > 10 | jest.mock('@actions/core', () => ({
         |            ^
      11 |   info: jest.fn(),
      12 |   setFailed: jest.fn(),
      13 |   getInput: jest.fn(),

Removing the following line from the test causes it to work, however it doesn't mock the API request so it doesn't pass:

fetchMock.mockResponseOnce(JSON.stringify({data: '12345'}))

Am I using this library incorrectly, or has something updated recently that causes this issue? It was working until recently. I'm on version ^3.0.2.