1

I want to force node-fetch to be a stub and I'm having a bit of trouble getting it to work. Code:

const fetchMock = jest.fn();

const {
  getArticle 
} = require('../../sfpublish/api');
console.log('loaded api')
const A = global.proxyquire('../../sfpublish/api', {
  'node-fetch': fetchMock
});

setup.js:

global.proxyquire = require('proxyquire');

package.json:

"jest": {
    "automock": false,
    "globalSetup": "./test/__config.js",
    "setupFiles": [
      "./test/__setup.js"
    ]
  },

Result:

FAIL  test/sfpublish/api.test.js
  ● Test suite failed to run

    Cannot find module '../../sfpublish/api'

      23 | } = require('../../sfpublish/api');
      24 | console.log('loaded api')
    > 25 | const A = global.proxyquire('../../sfpublish/api', {
         |                  ^
      26 |   'node-fetch': fetchMock
      27 | });

How can it be failing to load the module that I just loaded 2 lines previous? Is proxyquire not the right module to use here?

I've gotten node-fetch to be a mock in my test but when I run the function in the module (which has const fetch = require('node-fetch'); at the top) it's going to the real module instead of the fake. I've tried using fetch mocking libs like fetch-mock to no avail.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
jcollum
  • 43,623
  • 55
  • 191
  • 321
  • Seems like it won't work. See this github comment - https://github.com/facebook/jest/issues/1937#issuecomment-346531494 – rkm Jul 19 '18 at 09:12

1 Answers1

0

I ended up putting a mock in:

test/__mocks__/node-fetch.js

'use strict';
const nodeFetch = jest.genMockFromModule('node-fetch');
module.exports = nodeFetch;

package.json:

 "jest": {
    "verbose": true,
    "automock": false,
    "globalSetup": "./test/__config.js",
    "coverageReporters": [
      "text-summary",
      "html"
    ],
    "roots": [
      "./test"
    ],
    "setupFiles": [
      "./test/__setup.js"
    ]
  }
jcollum
  • 43,623
  • 55
  • 191
  • 321