wheresrhys/fetch-mock

Mockery doesn't work as expected

timnew opened this issue · 5 comments

I setup the mockery and fetch-mock as following code:

import mockery from 'mockery'
import fetch from 'node-fetch'
import fetchMock from 'fetch-mock'
import MyModule from './MyModule'

fetchMock.useNonGlobalFetch(fetch)
// ...
    beforeEach(() => {
      mockery.enable({ useCleanCache: true })
      mockery.registerMock('node-fetch', fetchMock.mock(pattern, 'POST', 200).getMock())
    })

    afterEach(() => {
      mockery.deregisterMock('node-fetch')
      mockery.disable()
    })

And during the test, I found the request doesn't get mocked as expected, all request hit the real server and fetchMock.called() returns false

Did I missed something or what should I do?!?!

You need to import MyModule after calling mockery.registerMock, which you can only do if using require('./MyModule'). I don't know if there are any other libraries that mock modules that deal with import better than mockery does. I doubt there are any though because they'd need to be pretty closely coupled with babel

I realized the issue, and trying to figure out a solution.
It is kind of painful while writing test for library rather than application.
I think the only way to solve the issue is to add another abstraction layer in the lib to enable developer to inject fetch ployfill into it.
Thanks for the help anyway

I'm also having the Problem, that fetchMock does not actually mock away my request, and requests are running against real url.
I am using import fetch from 'isomorphic-fetch'; in my react action.
I cant use mockery since it does not work with Webpack (mfncooper/mockery#37). Do you have any different Idea?

try import 'isomorphic-fetch' instead of import fetch from 'isomorphic-fetch';

Great! I then first ran into #60 but with adding require('isomorphic-fetch'); before my actual tests (e.g. loadtests.js) now everything runs smooth. You saved my day (and my code) Thanks!!