Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FetchMock.getMock seems always undefined as of 4.0.0 #56

Closed
dschulten opened this issue Jan 1, 2016 · 2 comments
Closed

FetchMock.getMock seems always undefined as of 4.0.0 #56

dschulten opened this issue Jan 1, 2016 · 2 comments

Comments

@dschulten
Copy link

I am using FetchMock with Mockery as Node 4 module, hence I need to get a handle on the mocked fetch() function.

Registering the node-fetch mock with myMock.getMock() as shown below leads to an undefined fetch function in the code under test.

'use strict';

var fetchMock = require('fetch-mock');
var mockery = require('mockery');

describe('fetch mockery', function () {

  beforeEach(function () {
    mockery.enable({useCleanCache: true});
    var myMock = fetchMock
      .mock('http://auth.service.com/user', '{"foo": 1}');
    mockery.registerMock('node-fetch', myMock.getMock());        <-- undefined
  });

  afterEach(function () {
    fetchMock.restore();
    mockery.deregisterMock('node-fetch');
    mockery.disable();
  });

  it('should mock a request', function () {

    var goFetch = require('../lib/fetchsample'); // just a call to fetch in a separate module

    return goFetch('http://auth.service.com/user').then(function (response) {
      return response.json();
    }).then(function (json) {
      console.log(json);
    });
  });

});

As a workaround, the necessary fetch function mock is availabe as myMock.mockedContext.fetch:

mockery.registerMock('node-fetch', myMock.mockedContext.fetch);

Maybe the fix would be to change getMock() in fetch-mock.js like so:

    /**
     * getMock
     * Returns a reference to the stub function used to mock fetch
     * @return {Function}
     */
    getMock () {
        return this.mockedContext.fetch;
    }

Or am I using fetch-mock incorrectly here?

@wheresrhys
Copy link
Owner

thanks for pointing this out. Not sure what in v4 would've broken it, or why the tests still pass. I'll fix the tests and add your solution

@wheresrhys
Copy link
Owner

Ah no, you're missing fetchMock.useNonGlobalFetch(require('node-fetch')); before your tests. That should fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants