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.

4

1 回答 1

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"
    ]
  }
于 2018-07-20T21:11:16.000 回答